繁体   English   中英

在pyparsing期间改变字符串

[英]change string during pyparsing

在我的pyparsing代码中,我有以下表达式:

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

我想将exp2中的foo更改为bar,以便我可以在已解析的数据中区分=和!=。 这可能吗?

Karl Knechtel的评论是有效的,但如果您想更改匹配的令牌,可以在解析操作中执行此操作。

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

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

将打印:

['booA', 'B']

如果您只想用常量文字字符串替换表达式,请使用replaceWith

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

打印:

['Z', 'B']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM