Hi lazycoder,

In researching this a bit I came across Parsing nested parentheses, which has lots of answers to a question similar to yours. There's also perlfaq6, Text::Balanced, and Regexp::Common::balanced.

For fun, I went all-out and parsed the string into a Perl data structure - this is probably overkill for you, but I'll post it anyways in case it's useful to someone.

First, the output:

$input = '(E,(A,B),(C,(X,Y,Z),D),F)'; $parsed = ['E,',['A,B'],',',['C,',['X,Y,Z'],',D'],',F']; $filtered = ['E,',',',',F']; $output = '(E,F)';

And the code:

use warnings; use strict; use 5.010; my ($LEFT,$RIGHT) = ('(',')'); use Regexp::Common qw/balanced/; sub parseparens { my ($str) = @_; return $str unless index($str,$LEFT)>=0; $str = substr $str,1,-1 if $str=~/^\Q$LEFT\E.*\Q$RIGHT\E$/; return [ map {parseparens($_)} split /$RE{balanced}{-parens=>$LEFT.$RIGHT}/, $str ]; } sub buildparens { my ($data) = @_; return $data unless ref $data; return join '', map {buildparens($_)} $LEFT, @$data, $RIGHT; } # $wanted gets the string elements in $_ and can manipulate them, # if it returns false the entire arrayref # which contains that string is filtered out sub filter { my ($data,$wanted) = @_; if (!ref $data) { local $_ = $data; return $wanted->() ? $_ : (); } my ($keep,@out) = (1); for my $e (@$data) { if (ref $e) { push @out, filter($e,$wanted); } else { local $_ = $e; $keep=0 unless $wanted->(); push @out, $_; } } return $keep ? \@out : (); } use Data::Dumper; $Data::Dumper::Terse=1; $Data::Dumper::Indent=0; my $input = '(E,(A,B),(C,(X,Y,Z),D),F)'; say " \$input = ", Dumper($input), ";"; my $parsed = parseparens($input); say " \$parsed = ", Dumper($parsed), ";"; warn "parse-/buildparens round trip failed: ".buildparens($parsed) unless buildparens($parsed) eq $input; my $filtered = filter($parsed, sub {!/\b(?:A|C)\b/}); say "\$filtered = ", Dumper($filtered), ";"; my $output = buildparens($filtered); $output=~s/,(?=,)//g; say " \$output = ", Dumper($output), ";";

The filter function can be implemented differently depending on the requirements. Also, I've kept the functions generic in that they don't care about the contents of the parentheses, which is why I manually squash the repeated commas at the end. (It's possible to make the functions care about commas by adding split /,/, ... and join ',', ... on input/output, but I removed that to simplify things.)

Hope this helps,
-- Hauke D


In reply to Re: How to use regex to get brackets surrounding something by haukex
in thread How to use regex to get brackets surrounding something by lazycoder

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.