understanding regexp with array notation
I've met this code snippet:
erb = "#coding:UTF-8 _erbout = ''; _erbout.concat ..." # string is cut
erb[/\A(#coding开发者_运维问答[:=].*\r?\n)/, 1]
I know how regular expression works, but I am confused with the array notation. What does it mean to place a regexp in []
, what does the second argument 1
mean?
str[regexp]
is actually a method of class String, you can find it here http://www.ruby-doc.org/core/classes/String.html#M001128
The second argument 1
will return text matching 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+)
The brackets are a method of String. See http://www.ruby-doc.org/core/classes/String.html:
If a Regexp is supplied, the matching portion of str is returned. If a numeric or name parameter follows the regular expression, that component of the MatchData is returned instead. If a String is given, that string is returned if it occurs in str. In both cases, nil is returned if there is no match.
The 1 means to return what's matched by the pattern inside the parenthesis.
精彩评论