Freeman Freeman - 1 month ago 7
Perl Question

Parenthesis in regular expressions

Using Perl and:

my $s="The Sea! The Sea!"


The pattern
/(.+)\s*\1/
matches
The Sea! The Sea!
because its matches the backreference
\1


However, the pattern
/((.+)\s*\1)/
does not match
The Sea! The Sea!


Why?

Answer
((.+)\s*\2)

should work because inner captured group has become #2 now as outermost group is captured group #1.

Note that you can also use relative numbering of groups i.e.

((.+)\s*\g{-1})

Where \g{-1} will match most recent captured group.

Comments