From: Brian Candler Date: 2010-02-07T05:23:59+09:00 Subject: Re: match/scan does not return multiple matches Michal Suchanek wrote: > Hello > > I tried scanning for multiple occurences of a group in a string and > match/scan would return only one. > > > "ajabcabck".match /^a*j(?:b*(a+)b+c*)+k$/ > => # > > "ajabcabck".scan /^a*j(?:b*(a+)b+c*)+k$/ > => [["a"]] > > > clearly the a+ group must match twice to match the string from ^ to $ > but only single match is returned. But the regular expression you're passing is anchored, so the entire regexp is only matched once, and it only contains one capturing group. Perhaps this is clearer: >> "abcd".scan /^a(b)(c)d$/ => [["b", "c"]] >> "abcd".scan /^a(?:(b|c)+)d$/ => [["c"]] >> In both cases the result is an array containing a single element, because the regexp was matched exactly once. The first gives [$1,$2] because there are two capture groups in its regexp. The second gives only [$1] because there is a single capture group. It happens to have matched multiple times, but you get only the last value for $1. If multiple values were inserted into the result, then you wouldn't know if ["foo","bar","baz"] came from [$1,$2,$3] or [$1,$1,$2] or [$1,$1,$1] or [$1,$2,$2] -- Posted via http://www.ruby-forum.com/.