4 回答

TA貢獻1802條經驗 獲得超5個贊
正則表達式嘗試盡可能多地匹配文本,從而消耗所有字符串。它不會在該字符串的某些部分上查找正則表達式的其他匹配項。這就是為什么你只得到一個答案。
解決方案是不使用正則表達式。如果您實際上正在嘗試解析數學表達式,請使用真正的解析解決方案。如果你真的只想捕獲括號內的碎片,只需在你看到(和)時遞增字符計數并遞增一個遞減計數器。

TA貢獻1804條經驗 獲得超7個贊
正如其他人所提到的,正則表達式不是嵌套構造的方法。我將使用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]
(手動完成換行/縮進/注釋)
編輯:修改以消除不必要的Forward,根據Paul McGuire的建議。
以嵌套列表格式獲取輸出:
res = parens.parseString("((12 + 2) + 3)")
res.asList()
輸出:
[[['12', '+', '2'], '+', '3']]
添加回答
舉報