pythonpyparsing

Use pyparsing to parse expression starting with parenthesis


I'm trying to develop a grammar which can parse expression starting with parenthesis and ending parenthesis. There can be any combination of characters inside the parenthesis. I've written the following code, following the Hello World program from pyparsing.

from pyparsing import *

select = Literal("select")

predicate = "(" + Word(printables) + ")"

selection = select + predicate

print (selection.parseString("select (a)"))

But this throws error. I think it may be because printables also consist of ( and ) and it's somehow conflicting with the specified ( and ).

What is the correct way of doing this?


Solution

  • You could use alphas instead of printables.

    from pyparsing import *
    
    select = Literal("select")
    predicate = "(" + Word(alphas) + ")"
    selection = select + predicate
    print (selection.parseString("select (a)"))
    

    If using { } as the nested characters

    from pyparsing import *
    
    expr = Combine(Suppress('select ') + nestedExpr('{', '}'))
    value = "select {a(b(c\somethinsdfsdf@#!@$@#@$@#))}"
    print( expr.parseString( value ) )
    
    output: [['a(b(c\\somethinsdfsdf@#!@$@#@$@#))']]
    

    The problem with ( ) is they are used as the default quoting characters.