in reply to Re: Replacement Regex
in thread Replacement Regex

This one will handle nested parens:

#!/usr/bin/perl -w use strict; $_ = '$a ($a (hi) $a) $a (()$a)'; my $re; $re = qr/(?:[^\(\)]*|\((??{$re})\))+/; s/(\($re\))|\$a/$1?$1:'$b'/eg; print;

Update: should've referred to perlre manpage instead of relying on memory, the version there makes it somewhat nicer:

my $re; $re = qr/\((?:(?>[^()]*)|(??{$re}))*\)/; s/($re)|\$a/$1?$1:'$b'/eg;

Update: It appears to broken in 5.6.0 (gives output as tachyon shows below), but it works for me with 5.6.1.

Replies are listed 'Best First'.
Re: Re: Re: Replacement Regex
by tachyon (Chancellor) on Mar 20, 2002 at 19:29 UTC

    <BEGIN_TEMPT_FATE>This one will handle nested parens:</END_TEMPT_FATE>

    $_ = '(($a $a hi) $a ($a) $a)'; my $re; $re = qr/\((?:(?>[^()]*)|(??{$re}))*\)/; s/($re)|\$a/$1?$1:'$b'/eg; print; __DATA__ (($a $a hi) $b ($a) $b)

    Oops!

    cheers

    tachyon

    s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

      $_ = '(($a $a hi) $a ($a) $a) $a ($a) $a '; my $re; ($re=$_) =~ s/((\()|(\))|.)/${['(','']}[!$2]\Q$1\E${[')','']}[!$3]/gs; $re = join'|',map{quotemeta}eval{/$re/}; die $@ if $@ =~ /unmatched/; s/($re)|\$a/$1?$1:'$b'/eg;