我在 python 中有一个这样的字符串
filter="eq(Firstname,test),eq(Lastname,ltest),OR(eq(ContactID,12345),eq(ContactID,123456))"
rx_comma = re.compile(r"(?:[^,(]|\([^)]*\))+")
result = rx_comma.findall(filter)
实际结果是:
['eq(Firstname,test)', 'eq(Lastname,ltest)', 'OR(eq(ContactID,12345)', 'eq(ContactID,123456))']
预期结果是:
['eq(Firstname,test)', 'eq(Lastname,ltest)', 'OR(eq(ContactID,12345),eq(ContactID,123456))']
感谢任何帮助。
最佳答案
虽然OP的问题已经通过使用regex
模块得到解决,但我想在这里介绍pyparsing作为替代解决方案。可以通过以下命令安装:
pip install pyparsing
代码:
import pyparsing as pp
s = "eq(Firstname,test),eq(Lastname,ltest),OR(eq(ContactID,12345),eq(ContactID,123456))"
expr = pp.delimited_list(pp.original_text_for(pp.Regex(r'.*?(?=\()') + pp.nested_expr('(', ')')))
output = expr.parse_string(s).as_list()
assert output == ['eq(Firstname,test)', 'eq(Lastname,ltest)', 'OR(eq(ContactID,12345),eq(ContactID,123456))']
说明:
关键点是上面代码中的expr
。我在其定义中添加了一些解释性注释,如下:
pp.delimited_list( # Separate a given string at the default comma delimiter
pp.original_text_for( # Get original text instead of completely parsed elements.
pp.Regex(r'.*?(?=\()') # Search everything before the first opening parenthesis '('
+ pp.nested_expr('(', ')') # Parse nested parentheses
)
)
关于python - 正则表达式用括号外的逗号分割字符串,并具有多个级别的python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71341796/