Keep It Simple, Stupid | |
PerlMonks |
Re^3: Is this a bug in perl regex engine or in my brain?by AnomalousMonk (Archbishop) |
on Oct 06, 2015 at 20:48 UTC ( [id://1143978]=note: print w/replies, xml ) | Need Help?? |
Looks like switching from It's a regex metacharacter/operator precedence issue.
The regex | (alternation) operator has a low (the lowest?) precedence among regex operators. When a raw string like The ^ start-of-string assertion is effectively grouped and evaluated with the (2[0-4]|1?[0-9])?[0-9] expression and disconnected by the alternation from the 25[0-5]$ expression. IOW, the regex will match any string with a [0-9] at the minimum (everything else is optional) at the start or with a 25[0-5] at the end, and nothing else in the string matters!
In contrast, choroba used a qr// operator to define the $regex object (in fact, a Regexp object). (Update: See qr// in Regexp Quote-Like Operators in perlop.) This is not the same as a raw string! Among other things, the qr// operator adds a non-capturing (?:pat) group around the whole expression that, in this application, effectively preserves the desired association between start- and end-of-string assertions after interpolation:
Bottom line: Wherever possible, prefer qr// to raw strings for regex expressions. Please see perlre, perlretut, and perlrequick.
Update: Incidentally, the regex qr/(2[0-4]|1?[0-9])?[0-9]|25[0-5]/ does not match the strings 000 001 012 etc. (Update: The regex does match 00 01 02 etc.) If this is an issue, I suggest Give a man a fish: <%-{-{-{-<
In Section
Seekers of Perl Wisdom
|
|