in reply to Re^2: Match a pattern only if it is not within another pattern
in thread Match a pattern only if it is not within another pattern

This is a good thing to try to remember; it can come up a lot.

Caveat: doesn't work if you need to support nested bar/qux pairs, e.g. only replacing the first and last foo in: foo bar foo bar foo qux foo qux foo

Replies are listed 'Best First'.
Re^4: Match a pattern only if it is not within another pattern
by Transient (Hermit) on Aug 16, 2005 at 19:56 UTC
    Just remove the ? from .+? to make it greedy and it will work.
Re^4: Match a pattern only if it is not within another pattern
by xdg (Monsignor) on Aug 16, 2005 at 20:04 UTC

    You can do the same thing but add Regexp::Common for arbitrary balanced delimiters;

    use Regexp::Common; my $orig = my $str = 'foo bar foo bar foo qux foo qux foo'; $str =~ s{ ( $RE{balanced}{-begin => "bar"}{-end => "qux"} ) | (foo) } { defined $2 ? 123 : $1 }xge; print "$orig\n"; print "$str\n";

    Result:

    foo bar foo bar foo qux foo qux foo 123 bar foo bar foo qux foo qux 123

    -xdg

    Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.