muruga muruga - 1 year ago 66
Perl Question

How can I highlight consecutive duplicate words with a Perl regular expression?

I want a Perl regular expression that will match duplicated words in a string.

Given the following input:

$str = "Thus joyful Troy Troy maintained the the watch of night..."

I would like the following output:

Thus joyful [Troy Troy] maintained [the the] watch of night...

Kip Kip
Answer Source

This works:

$str =~ s/\b((\w+)\s+\2)\b/[\1]/g;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download