change string during pyparsing

2020-07-17 07:13发布

问题:

In my pyparsing code I have the following expressions:

exp1 = Literal("foo") + Suppress(Literal("="))  + Word(alphanums+'_-')
exp2 = Literal("foo") + Suppress(Literal("!=")) + Word(alphanums+'_-')
exp = Optional(exp1) & Optional(exp2)

I want to change foo in exp2 to bar, so that I can distinguish between = and != in the parsed data. Is this possible?

回答1:

Karl Knechtel's comment is valid, but if you want to change a matched token, you can do this in a parse action.

def changeText(s,l,t):
    return "boo" + t[0]

expr = Literal("A").setParseAction(changeText) + "B"
print expr.parseString("A B").asList()

Will print:

['booA', 'B']

If you just want to replace an expression with a constant literal string, use replaceWith:

expr = Literal("A").setParseAction(replaceWith("Z")) + "B"
print expr.parseString("A B").asList()

prints:

['Z', 'B']