lazycoder has asked for the wisdom of the Perl Monks concerning the following question:

I have a data looking like : $data = (E,(A,B),(C,D),F) When searching for a character, I need all the characters in the searched character bracket. and remove it from $data. Eg : If searching for E, $data = (A,B),(C,D) $output = (E,F) Is there any regex for it?
  • Comment on How to use regex to get brackets surrounding something

Replies are listed 'Best First'.
Re: How to use regex to get brackets surrounding something
by BrowserUk (Patriarch) on Apr 09, 2016 at 01:52 UTC

    The original question: I have a data looking like : $data = (D,(A,B),C) When searching for A, I want to extract (A,B) and cut it out form the $data. I am not sure how to get the nearest "(" of A. Is there a regex for that?

    Not the clearest description, but if you mean you want to search for 'A', and remove it and everything within the nearest set of enclosing parens:

    $data = '(D,(A,B),C)';; $data =~ s{(\([^(]*A[^)]*\))}{} and print "$1\n$data";; (A,B) (D,,C)

    Note: the stuff removed is also available in $1.


    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority". I knew I was on the right track :)
    In the absence of evidence, opinion is indistinguishable from prejudice.
      Yup thats what I wanted. Thanks!
      I missed something. I updated the question.
Re: How to use regex to get brackets surrounding something
by haukex (Archbishop) on Apr 09, 2016 at 13:46 UTC

    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:

    Hope this helps,
    -- Hauke D

Re: How to use regex to get brackets surrounding something
by fishy (Friar) on Apr 09, 2016 at 11:54 UTC
Re: How to use regex to get brackets surrounding something
by 1nickt (Canon) on Apr 09, 2016 at 05:42 UTC

    Is your data a string? Where does it come from?

    There's probably a better way to accomplish what your main goal is. If you describe your situation a little more fully you'll probably get some good suggestions.

    XY Problem


    The way forward always starts with a minimal test.