| Next | Regular Expression Mastery | 83 |
How does a human decide that ((I)(like(pie))!) is balanced?
( ( I ) ( l i k e ( p i e ) ) ! )
1 2 1 2 3 2 1 0
That's what we'll do:
^
(?{ 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.
)
$
/x was essential here:
^(?{local$d=0})(?:\((?{$d++})|\)(?{$d--})(?(?{$d<0})(?!))|(?>[^()]*))*(?(?{$d!=0})(?!))$
Similarly: Recognize palindromes:
/^(.*).?(?>(.*))(?(?{$1 ne reverse $2})(?!))/
| Next | ![]() |
Copyright © 2002 M. J. Dominus |