in reply to search for matching parentheses

I think your life would be a lot happier if you abandoned the idea of using regular expressions for this task and looked at Text::Balanced instead.

--
<http://dave.org.uk>

"The first rule of Perl club is you do not talk about Perl club."
-- Chip Salzenberg

Replies are listed 'Best First'.
Re^2: search for matching parentheses
by Anonymous Monk on Oct 20, 2006 at 23:22 UTC
    Wow, thank you ALL for your prompt replies! So many options... :-)
    I decided to check out the module Text::Balanced, since it seems it could be useful to me not just for this problem but in the future.
    But... I'm having some problems with it. I'm wondering why the below code does not work. I'm expecting this piece of code to extract "(x,y,z)", and put ", Param2(1,2,3), Param3(a,b,c)" in the remainder, and "Param1" in the prefix. But it doesn't work. It puts everything in the remainder.
    $string = "Param1(x,y,z), Param2(1,2,3), Param3(a,b,c)"; print "Original string: ", $string, "\n"; ($ext,$rem,$pre) =extract_bracketed($string,'()','.*?'); print "extracted: ", $ext, "\n"; print "remainder: ", $rem, "\n"; print "skip pref: ", $pre, "\n";
    Any help would be greatly appreciated.
    Thanks! Emma

      It seems to work like this:

      use Text::Balanced qw(extract_bracketed); my $string = "Param1(x,y,z), Param2(1,2,3), Param3(a,b,c)"; print "Original string: ", $string, "\n"; my ($ext,$rem,$pre) = extract_bracketed($string, '()', '[^(]*'); print "extracted: $ext\n"; print "remainder: $rem\n"; print "prefix: $pre\n";

      All I've really changed is the prefix regex. I'm now saying that the prefix is one or more non-bracket characters. I'm a little confused tho' - I'd expect that to be the default behaviour.

      --
      <http://dave.org.uk>

      "The first rule of Perl club is you do not talk about Perl club."
      -- Chip Salzenberg