Use pyparsing to parse expression starting with parenthesis

Question:

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?

Asked By: aandis

||

Answers:

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(csomethinsdfsdf@#!@$@#@$@#))}"
print( expr.parseString( value ) )

output: [['a(b(c\somethinsdfsdf@#!@$@#@$@#))']]

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

Answered By: Jerome Anthony
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.