Next Regular Expression Mastery 83

Matching Strings with Balanced Parentheses

     ( ( I ) ( l i k e ( p i e ) ) ! )        
     1 2   1 2         3       2 1   0
     ^
     (?{ local $d=0 }) # Set depth to 0
     (?:                  
         \(            # When you see an open parenthesis...
         (?{$d++})     #  ...increment the depth
      |  
         \)            # or you could see a close parenthesis...
         (?{$d--})     #  ...in which case decrement the depth...
         (?            #  ...and check...
           (?{$d<0})   #  ...if there was no matching open paren...
           (?!)        #  ...then fail.
         )  
      |      
         (?> [^()]* )  # or you could see some non-parenthesis text
                       # (but don't bother backtracking into it)
     )* 
                       # After you match as much as possible...
     (?                # ...check to see if...
       (?{$d!=0})      # ...there were unmatched open parentheses...
       (?!)            # ...if so then fail.
     )
     $

^(?{local$d=0})(?:\((?{$d++})|\)(?{$d--})(?(?{$d<0})(?!))|(?>[^()]*))*(?(?{$d!=0})(?!))$

/^(.*).?(?>(.*))(?(?{$1 ne reverse $2})(?!))/



Next Copyright © 2002 M. J. Dominus