I'm trying to match a string like (something is something).
$_ = "anna is ann";
if (/([a-zA-Z]+) is \1/) {
print "matched\n";
}
I expected this not to work, but it works. Why?
Try print $1; or print $&; - /([a-zA-Z]+) is \1/ matches the a is a substring of anna is ann. If you want to restrict the match, you might want to anchor to the beginning and/or end of the string (or line, under /m) with ^ resp. $, or use the word boundary \b if you want to match within a longer string. So:
/^([a-zA-Z]+) is \1$/ will match "anna is anna" but not "anna is ann" or "anna is anna ".
/\b([a-zA-Z]+) is \1\b/ will match "x anna is anna y" and "sue-ann is ann-marie" but not "anna is ann", "anna is anne", or "anna is annabelle".
It matches 6 chars starting at pos 3 (a is a). Perhaps you should have used
/^([a-zA-Z]+) is \1\z/
[a-zA-Z]+ matches 4 chars at pos 0.
is matches 4 chars at pos 4.\1 doesn't match at pos 8: Backtrack.[a-zA-Z]+ matches 3 chars at pos 0.
is doesn't match at pos 3: Backtrack.[a-zA-Z]+ matches 2 chars at pos 0.
is doesn't match at pos 2: Backtrack.[a-zA-Z]+ matches 1 chars at pos 0.
is doesn't match at pos 1: Backtrack.[a-zA-Z]+ matches 3 chars at pos 1.
is matches 4 chars at pos 4.\1 doesn't match at pos 8: Backtrack.[a-zA-Z]+ matches 2 chars at pos 1.
is doesn't match at pos 3: Backtrack.[a-zA-Z]+ matches 1 chars at pos 1.
is doesn't match at pos 2: Backtrack.[a-zA-Z]+ matches 2 chars at pos 2.
is matches 4 chars at pos 4.\1 doesn't match at pos 8: Backtrack.[a-zA-Z]+ matches 1 chars at pos 2.
is doesn't match at pos 3: Backtrack.[a-zA-Z]+ matches 1 char at pos 3.
is matches 4 chars at pos 4.\1 matches 1 char at pos 8.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With