RegEx for matching brackets

John Machin sjmachin at lexicon.net
Thu May 1 20:22:50 EDT 2008


On May 2, 9:44 am, NevilleDNZ <neville... at gmail.com> wrote:
> 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

Regexes can't count.

To check for balanced braces, you need to write code e.g.

# untested
def balanced_braces(s):
   n = 0
   for c in s:
      if c == '{':
         n += 1
      elif c == '}':
         n -= 1
         if n < 0:
            return False
   return n == 0

HTH,
John



More information about the Python-list mailing list