in reply to regex/substitution question
my %subs = ( foo => 'bar', bar => 'baz', );
"foo" my end up being substituted with "baz".
You want to search for all regex in the same pass
s/(foo|bar)/$subs{$1}/g
And you want to search for the longest matches first.
s/(Xaa11|Xaa1)/$subs{$1}/g
So what you want is
my $pat = join '|', map quotemeta, sort { length($b) <=> length($a) } +keys(%subs); s/($pat)/$subs{$1}/g;
Alternatively, if you're always matching entire words, you could forgo the sorting in favour of using anchors.
my $pat = join '|', map quotemeta, keys(%subs); s/\b($pat)\b/$subs{$1}/g;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: regex/substitution question
by slugger415 (Monk) on Feb 07, 2012 at 19:32 UTC | |
by ikegami (Patriarch) on Feb 07, 2012 at 21:43 UTC |