首页 > 解决方案 > 获取括号表达式的所有部分

问题描述

我需要一个正则表达式,它返回带括号的字符串的所有部分。

一个例子是:

if ((a and b) or (a and)) or (c and d) or (e and f)

会回来

['if', '((a and b) or (a and))', 'or', '(c and d)', 'or', '(e and f)']

.

任何人都可以指导我如何实现它?不幸的是,我与re的友谊并不深。

最大的问题是“括号内的括号”。

非常感谢。

标签: pythonregex

解决方案


正则表达式无法进行深度括号匹配。

如果你有一个固定的模式,你可以做到这一点——比如三个深括号,以及顶层括号中的第二组兄弟,依此类推。但是仅使用正则表达式将任意右括号与左括号匹配并不容易(如果有一种实用的方法可以使用正则表达式)。

编写几行 Python 代码并使用 Python 本身来匹配外括号组要容易得多——因为您可以只计算流中开括号的数量。所以,沿着这个方向做一些事情 - (它可以用更少的行来制作):

def extract_parentheses_groups(text):
    count = 0
    groups = []
    buffer = ""
    for char in text:
       if char == "(":
            if count == 0 and buffer.strip():
                groups.append(buffer.strip())
                buffer = ""
            count += 1
       buffer += char
       if char == ")":
            count -= 1
            if count == 0:
                groups.append(buffer.strip())
                buffer = ""
    if buffer.strip():
         groups.append(buffer.strip())
    return groups

通过这个运行你的示例输入,我得到:

In [17]: a = """if ((a and b) or (a and)) or (c and d) or (e and f)"""

In [18]: extract_parentheses_groups(a)
Out[18]: ['if', '((a and b) or (a and))', 'or', '(c and d)', 'or', '(e and f)']

推荐阅读