Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: Parsing nested parentheses

by TheDamian (Priest)
on Nov 18, 2003 at 20:15 UTC ( #308104=note: print w/ replies, xml ) Need Help??


in reply to Parsing nested parentheses

This is reasonably straightforward with Regexp::Common, though you do have to "roll-your-own" a little:

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"; }
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.

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).


Comment on Re: Parsing nested parentheses
Download Code
Replies are listed 'Best First'.
Re: Re: Parsing nested parentheses
by JeffR100 (Acolyte) on Nov 18, 2003 at 22:57 UTC
    I tried this out, but it give a segmentation fault on the line: $from =~ m/( \( $nested \) | \Q$want\E )/x; Any ideas?
      Any ideas?
      Not without a little more information. What version of perl are you using? What version of Regexp::Common?

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://308104]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (20)
As of 2015-07-07 22:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (93 votes), past polls