Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Help modifying recursive regex

by gurpreetsingh13 (Scribe)
on May 08, 2013 at 05:25 UTC ( #1032577=note: print w/ replies, xml ) Need Help??


in reply to Help modifying recursive regex

Yes, splitting is the simple solution.

sub get_groups { my @groups = (); my $level = 0; my $group = ""; #Keep on increasing the level once you find the opening brace. #After coming out of loop, level should be again 0 foreach my $val ( split //, shift ) { next if $val =~/\s/; if ( $level == 0 && !($val ~~ [ "(", ")" ]) ) { push @groups, +$val; next; } if ( $level != 0 && !($val ~~ [ "(", ")" ]) ) { $group.=$val; +next; } if ( $val eq "(" && $level==0) { $level++;$group = ""; next; } if ( $val eq "(" && $level!=0) { $level++;$group .= "("; next; + } if ( $val eq ")" && $level==1) {$level--;push @groups, $group; + $group = ""; next; } if ( $val eq ")" && $level!=1) {$level--;$group .= ")"; next; +} } print Dumper(@groups); } ## ---------- end sub get_groups

Input:

my $string = "A (B C D)"; get_groups($string); $string = "A (B C D) (E F G)"; get_groups($string); $string = "A B (C (D E) (F G)) (H I)"; $string = "(A B) M N ((C (D E)) (F G)) (Z(H I)) T R"; get_groups($string);

Output: $VAR1 = 'A'; $VAR2 = 'BCD'; $VAR1 = 'A'; $VAR2 = 'BCD'; $VAR3 = 'EFG'; $VAR1 = 'AB'; $VAR2 = 'M'; $VAR3 = 'N'; $VAR4 = '(C(DE))(FG)'; $VAR5 = 'Z(HI)'; $VAR6 = 'T'; $VAR7 = 'R';


Comment on Re: Help modifying recursive regex
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1032577]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (23)
As of 2014-07-30 14:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (234 votes), past polls