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';

Create A New User
Node Status?
node history
Node Type: note [id://1032577]
help
Chatterbox?
and the voices are still...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (1)
As of 2017-12-16 23:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
What programming language do you hate the most?

Results (459 votes). Check out past polls.

Notices?