join "|", map { "\\b$_\\b" } reverse sort keys %cats;
I'd suggest putting a quotemeta in there, just to play it safe. Although I agree that using a proper parser is better! skooma: See also Building Regex Alternations Dynamically.
use warnings; use strict; use Test::More; my %cats = (blackcat=>5, whitecat=>10,orangecat=>20); my ($regex) = map { qr/\b($_)\b/ } join '|', map {quotemeta} sort { length $b <=> length $a or $a cmp $b } keys %cats; diag explain $regex; sub do_replace { my $input = shift; $input =~ s/$regex/$cats{$1}/g; return $input; } is do_replace("log10(blackcat)"), "log10(5)"; is do_replace("log10(blackcat)*whitecat*(log10(orangecat))"), "log10(5)*10*(log10(20))"; done_testing; __END__ # qr/\b(orangecat|blackcat|whitecat)\b/ ok 1 ok 2 1..2
In reply to Re^2: Is there any way to ignore certain words when substituing?
by haukex
in thread Is there any way to ignore certain words and keep it as it is when substituing hash values to a matched pattern in a string?
by skooma
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |