I’d like to use pyparsing to parse an expression of the form: expr = '(gimme [some {nested [lists]}])', and get back a python list of the form: [[['gimme', ['some', ['nested', ['lists']]]]]]. Right now my grammar looks like this:
nestedParens = nestedExpr(‘(‘, ‘)’)
nestedBrackets = nestedExpr(‘[‘, ‘]’)
nestedCurlies = nestedExpr(‘{‘, ‘}’)
enclosed = nestedParens | nestedBrackets | nestedCurlies
Presently, enclosed.searchString(expr) returns a list of the form: [[['gimme', ['some', '{nested', '[lists]}']]]]. This is not what I want because it’s not recognizing the square or curly brackets, but I don’t know why.
Here’s a pyparsing solution that uses a self-modifying grammar to dynamically match the correct closing brace character.
prints:
Updated: I posted the above solution because I had actually written it over a year ago as an experiment. I just took a closer look at your original post, and it made me think of the recursive type definition created by the
operatorPrecedencemethod, and so I redid this solution, using your original approach – much simpler to follow! (might have a left-recursion issue with the right input data though, not thoroughly tested):Gives:
EDITED:

Here is a diagram of the updated parser, using the railroad diagramming support coming in pyparsing 3.0.