Freeman
Freeman

Reputation: 6226

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?

Upvotes: 0

Views: 76

Answers (1)

anubhava
anubhava

Reputation: 786091

((.+)\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.

Upvotes: 10

Related Questions