in reply to Parsing nested parentheses
Note that I've assumed that, in the edge case where the target is unnested (e.g. 'F' in the above example), the extraction should just return target itself.use Regexp::Common; my $balanced = qr/[^()]+|$RE{balanced}{-parens=>'()'}/; sub extract { my ($want, $from) = @_; my $nested = qr/$balanced* \Q$want\E $balanced*/x; $from =~ m/( \( $nested \) | \Q$want\E )/x; return $1; } my $expr = '(((B,G),A,(A,B)),C,(D,(E))),F'; for ('A'..'H') { print "$_: ", extract($_,$expr),"\n"; }
Also note the standard regexish "left-most-longest-match" behaviour when the target appears more than once (as do targets 'A' and 'B' in the example).
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Parsing nested parentheses
by JeffR100 (Acolyte) on Nov 18, 2003 at 22:57 UTC | |
by TheDamian (Vicar) on Nov 18, 2003 at 23:42 UTC |