in reply to extract info from parentheis

Hello xiaoyafeng,

What’s wrong with a straightforward regex?

#! perl use strict; use warnings; $_ = 'the users contain (bbc (333)) BLAH BLAH (ddc (223)) BLAH BLAH(cc +c (123))'; print "Name: $1, ID: $2\n" while / \( ([^(\s]+) \s* \( ([^)]+) \)\) /g +x;

Output:

16:17 >perl 1194_SoPW.pl Name: bbc, ID: 333 Name: ddc, ID: 223 Name: ccc, ID: 123 16:17 >

Update: The module Text::Balanced has an extract_bracketed function which might be worth investigating.

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Replies are listed 'Best First'.
Re^2: extract info from parentheses
by davido (Cardinal) on Mar 21, 2015 at 17:45 UTC

    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