Capture literal brackets inside brackets in pyparsing

一曲冷凌霜 提交于 2019-12-23 22:00:47

问题


I'm trying to parse some functions arguments with PyParsing but am having trouble getting the right syntax. Namely, given:

str = "(key=val())"

I would like the parser to return ['key', 'val()'].

I've been trying to get this to work with the following code; the .suppress() calls are intentionally omitted for clarity.

ob = Literal("(")
cb = Literal(")")
key = Word(alphas)
value = Word(alpha + "()") 
parser = ob + key + "=" + value + cb
print parser.parseString(str)

but of course it's matching the final closing bracket as well and so I get a ParseException.

Is there an elegant solution to this? For example, I looked at nestedExpr but in this case it's not strictly a nesting since I want the val() to be treated as a literal. Similarly this question alludes to the problem but doesn't give a solution.


回答1:


Your definition of

value = Word(alpha + "()")

is overly liberal. Not only will it match trailing ()'s, but also any embedded ones, and regardless of matching opening and closing, values like:

SLDFJJ(sldkjf)
sdlkfj(sldkfj(lkskdjf)))(

and even just:

(((((())(()()()()

I suggest you define the syntax for an identifier, usually something like:

identifier = Word(alphas+'_', alphanums+'_')

and then compose value with:

value = Combine(identifier + '()')

Now the value expression won't erroneously accept any embedded ()s, and will only parse the trailing () and nothing further.



来源:https://stackoverflow.com/questions/35420067/capture-literal-brackets-inside-brackets-in-pyparsing

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