RegEx for matching brackets

NevilleDNZ nevillednz at gmail.com
Thu May 1 19:44:34 EDT 2008


Below is a (flawed) one line RegEx that checks curly brackets (from
awk/c/python input) are being matched.  Is there a one liner for doing
this in python?

ThanX
N

re_open_close="(((\{))[^{}]*((?(0)\})))+"
re_open_close=re.compile(re_open_close)
tests="""
  { this is a test  BAD
  { this is a test } OK
  { this is a test } { this is a test } OK
  { this is a test } { this { this is a test } is a test } OK
  { this is a test  { this { this is a test } is a test } missing
close BAD
""".splitlines()[1:]
for test in tests:
  if bool(re_open_close.search(test)) == bool(re.search("OK",test)):
    print "DETECTED:",test
  else:
    print "MISSED:",test
[linux]$ python ./re_matching.py
DETECTED:   { this is a test  BAD
DETECTED:   { this is a test } OK
DETECTED:   { this is a test } { this is a test } OK
DETECTED:   { this is a test } { this { this is a test } is a test }
OK
MISSED:   { this is a test  { this { this is a test } is a test }
missing close BAD



More information about the Python-list mailing list