change string during pyparsing

雨燕双飞 提交于 2019-12-06 04:20:54

问题


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']


来源:https://stackoverflow.com/questions/24954340/change-string-during-pyparsing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!