I often think Text::Balanced is going to be the answer, but after I implement a solution using Text::Balanced I'm rarely satisfied that it is the least complex solution:

use strict; use warnings; use Text::Balanced 'extract_bracketed'; my $string = q/the users contain (bbc (333)) BLAH BLAH (ddc (223)) BLA +H BLAH(ccc (123))/; while( length $string ) { my( $name, $id, $rest ) = extract_record($string); print "Name: $name, ID: $id\n"; $string = $rest; } sub extract_record { my $string = shift; my( $unwanted, $wanted, $rest ) = extract($string); return (extract($wanted))[0,1], $rest; } sub extract { my $input = shift; my( $balanced, $rest, $prefix ) = extract_bracketed($input, '()', +qr/[^(]*/); $balanced =~ s/^\(|\)$//g if length $balanced; return map { trim($_) } $prefix, $balanced, $rest; } sub trim { my $string = shift; $string =~ s/^\s+|\s+$//g; return $string; }

Regexp::Common has Regexp::Common::balanced which would probably facilitate a reasonably robust and possibly less complicated solution (left as an exercise for the reader, as I've lost interest at this point. ;)

Update: But a pure-regexp approach would work for data that is relatively simple, as the OP's data seems to be:

my $string = q/the users contain (bbc (333)) BLAH BLAH (ddc (223)) BLA +H BLAH(ccc (123))/; my $re = qr/ \( (?<name> [^(]+ ) # Capture name. \( (?<id> [^)]+ ) # Capture ID. \)\) # Closing parens. /x; print "Name: $+{name}, ID: $+{id}\n" while $string =~ m/$re/g;

...which is pretty much back to what you started with. ;)


Dave


In reply to Re^2: extract info from parentheses by davido
in thread extract info from parentheis by xiaoyafeng

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.