Python parsing bracketed blocks

Martin picture Martin · Oct 30, 2009 · Viewed 32.5k times · Source

What would be the best way in Python to parse out chunks of text contained in matching brackets?

"{ { a } { b } { { { c } } } }"

should initially return:

[ "{ a } { b } { { { c } } }" ]

putting that as an input should return:

[ "a", "b", "{ { c } }" ]

which should return:

[ "{ c }" ]

[ "c" ]

[]

Answer

PaulMcG picture PaulMcG · Oct 31, 2009

Or this pyparsing version:

>>> from pyparsing import nestedExpr
>>> txt = "{ { a } { b } { { { c } } } }"
>>>
>>> nestedExpr('{','}').parseString(txt).asList()
[[['a'], ['b'], [[['c']]]]]
>>>