简体   繁体   English

用于解析逗号之间的 Python 指令列表的正则表达式

[英]Regular expression to parse list of Python instructions between commas

I am writing a parser and, at some point, I am expecting a list of Python instructions and/or values written between commas.我正在编写一个解析器,在某些时候,我期待在逗号之间写入 Python 指令和/或值的列表。 For example,例如,

n >= 5, n < 20, m == len([1, 2, 3]), m + 1 == func(myObject.myMethod());

This is just an example, in practice I would like to be able to parse any valid Python expression.这只是一个例子,实际上我希望能够解析任何有效的 Python 表达式。

My grammar has a rule of the form:我的语法有以下形式的规则:

EXPRESSION ("," EXPRESSION)* ";"

where EXPRESSION is a regular expression that can accept any Python instruction.其中EXPRESSION是一个可以接受任何 Python 指令的正则表达式。 Of couse, since the comma could appear as part of my expression, I don't know how I could use it as a separator.当然,由于逗号可能会出现在我的表达式中,我不知道如何将它用作分隔符。 Still, seems to me like there must be a regular expression, since any human can clearly parse the four expressions in the example above.尽管如此,在我看来必须有一个正则表达式,因为任何人都可以清楚地解析上面示例中的四个表达式。 Any ideas?有任何想法吗?

My current regex is EXPRESSION = [^,;]+ but this of course only works for very simple cases;我当前的正则表达式是EXPRESSION = [^,;]+但这当然只适用于非常简单的情况; the example above cannot be parsed with this.上面的例子不能用这个来解析。

This is not possible, as a comma in a Python instruction may be misinterpreted as a separator, but still yield valid Python instructions.这是不可能的,因为 Python 指令中的逗号可能会被误解为分隔符,但仍会产生有效的 Python 指令。

Here is an example:下面是一个例子:

a = 1, b = ((2, 3), 4), a, b = b, a, b = a

This can be interpreted as:这可以解释为:

a = 1
b = ((2, 3), 4), a
b = b, a
b = a

Or as:或作为:

a = 1
b = ((2, 3), 4)
a, b = b
a, b = a

Or as:或作为:

a = 1
b = ((2, 3), 4)
a, b = b, a
b = a

All are valid pieces of code.都是有效的代码段。 There is no way you can know which is the intended one.您无法知道哪个是预期的。

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

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