in reply to Regex help

s///g won't search replaced text, as shown in the following snippet:

$search_for = '[string]'; $user = '[user]'; local $_ = 'foo [string] bar [string] baz'; s/(\Q$search_for\E)/__${user}__${1}__/g; print("$_\n"); # foo __[user]__[string]__ bar __[user]__[string]__ baz

You can use s///ge if you need to generate $user dynamically for each match.

Replies are listed 'Best First'.
Re^2: Regex help
by snacktime (Sexton) on Jun 02, 2005 at 17:54 UTC
    Silly me, I forgot what the problem was and mistated it. The problem is that the string I am searching for can exist as a substring of another element of @contexts, but I don't want it to match if it's already been rewritten.

    For example in the list I am looping through, one element could be demo-outgoing, and a later element could be demo. I don't want the string demo in the already formatted string __user__demo-outgoing__ to be matched and rewritten again.

    Does that make sense?

      So @context contains search strings? (This is why it's important to give a runable piece of code, including sample input. It takes the guessing out of the game.)

      my @contexts = qw( demo-outgoing demo ); local $_ = 'foo demo-outgoing bar'; my $regexp = join('|', map { quotemeta($_) } @contexts); s/($regexp)/__user__${1}__/g; print("$_\n"); # foo __user__demo-outgoing__ bar