三国纷争
正如其他人所提到的,正则表达式不是嵌套构造的方法。我将使用pyparsing给出一个基本的例子:import pyparsing # make sure you have this installedthecontent = 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']]