Regex for nested {}

Paul McGuire ptmcg at austin.rr.com
Fri Jul 29 02:16:38 EDT 2005


Or use pyparsing, and do both at the same time (that spark example
looks like a lot of work!).

Download pyparsing at http://pyparsing.sourceforge.net.

-- Paul


from pyparsing import *

text = """
    outer {
        inner1 { ...1 }
        inner2 { ...2 }
    }
    simple { ...3 }
    null {}
    single { blah }
"""

LBRACE = Literal("{").suppress()
RBRACE = Literal("}").suppress()

listKey = Word(alphanums)
listValue = Forward()
listEntry = Group( listKey + listValue )
listValue << Group( LBRACE +
                ZeroOrMore( listEntry | Word(alphanums+".") ) +
                RBRACE)

inputData = OneOrMore( listEntry )

results = inputData.parseString( text )

print results.asList()


Prints :
[['outer', [['inner1', ['...1']], ['inner2', ['...2']]]], ['simple',
['...3']], ['null', []], ['single', ['blah']]]

(manually formatted to show nesting)
[
  ['outer',
      [
        ['inner1', ['...1']],
        ['inner2', ['...2']]
      ]
  ],
  ['simple', ['...3']], 
  ['null', []], 
  ['single', ['blah']]
]




More information about the Python-list mailing list