我正在尝试匹配具有嵌套括号的类似数学表达式的字符串。
import re
p = re.compile('\(.+\)')
str = '(((1+0)+1)+1)'
print p.findall(s)
['(((1+0)+1)+1)']
我希望它匹配所有包含的表达式,例如 (1+0)、((1+0)+1)...
我什至不在乎它是否匹配不需要的东西,比如 (((1+0),我可以处理这些。
为什么它还没有这样做,我该如何做?
最佳答案
正如其他人所提到的,正则表达式不是用于嵌套结构的方式。我将使用 pyparsing 给出一个基本示例:
import pyparsing # make sure you have this installed
thecontent = pyparsing.Word(pyparsing.alphanums) | '+' | '-'
parens = pyparsing.nestedExpr( '(', ')', content=thecontent)
这是一个用法示例:
>>> parens.parseString("((a + b) + c)")
输出:
( # all of str
[
( # ((a + b) + c)
[
( # (a + b)
['a', '+', 'b'], {}
), # (a + b) [closed]
'+',
'c'
], {}
) # ((a + b) + c) [closed]
], {}
) # all of str [closed]
(手动换行/缩进/注释)
编辑:根据 Paul McGuire 的建议进行修改以消除不必要的 Forward
。
获取嵌套列表格式的输出:
res = parens.parseString("((12 + 2) + 3)")
res.asList()
输出:
[[['12', '+', '2'], '+', '3']]
关于Python:如何将嵌套括号与正则表达式匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5454322/