您没有确切说明函数的规格是什么,但是这种行为对我来说似乎是错误的:
>>> ParseNestedParen('(a)(b)(c)', 0)['a)(b)(c']>>> nested_paren.ParseNestedParen('(a)(b)(c)', 1)['b']>>> nested_paren.ParseNestedParen('(a)(b)(c)', 2)['']您的代码的其他注释:
- Docstring说“ generate”,但是函数返回一个列表,而不是生成器。
- 由于只返回了一个字符串,为什么要在列表中返回它?
- 函数在什么情况下可以返回字符串
fail
? - 反复调用
re.findall
然后丢弃结果是浪费的。 - 您尝试重新平衡字符串中的括号,但一次只能这样做一个括号:
>>> ParseNestedParen(')' * 1000, 1)RuntimeError: maximum recursion depth exceeded while calling a Pythonobject
正如Thomi在您所链接的问题中所说的那样,“正则表达式确实是完成这项工作的错误工具!”
解析嵌套表达式的通常方法是使用堆栈,方法如下:
def parenthetic_contents(string): """Generate parenthesized contents in string as pairs (level, contents).""" stack = [] for i, c in enumerate(string): if c == '(': stack.append(i) elif c == ')' and stack: start = stack.pop() yield (len(stack), string[start + 1: i])>>> list(parenthetic_contents('(a(b(c)(d)e)(f)g)'))[(2, 'c'), (2, 'd'), (1, 'b(c)(d)e'), (1, 'f'), (0, 'a(b(c)(d)e)(f)g')]


