Understanding regex with array writing

I met this piece of code:

erb = "#coding:UTF-8 _erbout = ''; _erbout.concat ..." # string is cut erb[/\A(#coding[:=].*\r?\n)/, 1] 

I know how a regex works, but I am confused by array notation. What does it mean to place a regular expression in [] , what does the second argument 1 mean?

+4
source share
2 answers

str[regexp] is actually a method of the String class, you can find it here http://www.ruby-doc.org/core/classes/String.html#M001128

The second argument 1 will return the text corresponding to the first subpattern #coding[:=].*\r?\n , another example for your better understanding:

 "ab123baab"[/(\d+)(ba+).*/, 0] # returns "123baab", since it is the complete matched text, ,0 can be omitted also "ab123baab"[/(\d+)(ba+).*/, 1] # returns "123", since the first subpattern is (\d+) "ab123baab"[/(\d+)(ba+).*/, 2] # returns "baa", since the second subpattern is (ba+) 
+3
source

Brackets are a String method. See http://www.ruby-doc.org/core/classes/String.html :

If Regexp is specified, the matching str part is returned. If a numeric or parameter name is followed by a regular expression, this component returns MatchData instead. If the string is String, this string if it occurs on str. In both cases, nil is returned if there is no match.

1 means returning what matches the pattern inside the bracket.

+2
source

Source: https://habr.com/ru/post/1348095/


All Articles