May 4, 2012, 8:13 AM
Post #1 of 3
Hi, if I use something like this:
What is captured within $1 if used with alternation?
"I love fred and barney" =~ /(barney|fred)/ ? print "$1\n" : print "No.\n";
it prints out fred. It suggests that the regex engine starts scanning the string from left to right searching whether any pattern on either side of the alternation matches it, and if it does, then that is stored inside $1 and the process ends.
But if I run something like this:
"I love fredder and fred" =~ /(fred|fredder)/ ? print "$1\n" : print "No.\n";
prints out fred. Surely while scanning from left, fredder comes first, so that should be stored in $1, but it is not. Not only that, whatever configuration be the strings fred and fredder in the regex and string, i.e fredder and fred and (fred|fredder), fred and fredder and (fred|fredder), fredder and fred and (fredder|fred), fred and fredder and (fredder|fred), it always outputs fred. Can anyone explain what is going on?