
zapzap
User
Nov 29, 2013, 3:47 PM
Post #1 of 10
(7772 views)
|
Matching brackets
|
Can't Post
|
|
Greetings, I have a string s = '[[][]]' How would I go about making sure all the brackets are closed 'properly' Something like '[[][[[]' is not considered closed properly I think I need a recursive type regex. I looked up turning off backtracking but I think that feature may have been removed, (besides I didn't really understand it anyway).
My approach: my $str2 = '[][[]'; my $str3 = "[[1,2,4],['words','dog'],[],[]]"; sub closedBrackets { $_ = shift; while( 1 ) { my $index1 = rindex($_,'['); my $index2 = index($_,']',$index1); return 1 if ($index1 < 0 && $index2 < 0); return if ($index1 > 0 && $index2 < 0) || ($index1 < 0 && $index2 > 0); $_ = substr($_,0,$index1) . substr($_,$index2+1); } } closedBrackets($str2) ? print $str2 . " ok\n" : print $str2 . " NOT ok\n"; closedBrackets($str3) ? print $str3 . " ok\n" : print $str3 . " NOT ok\n"; There should be a much nicer approach, more concise, possibly soleley with a regex?
|