python - 获取括号表达式的所有部分
问题描述
我需要一个正则表达式,它返回带括号的字符串的所有部分。
一个例子是:
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的友谊并不深。
最大的问题是“括号内的括号”。
非常感谢。
解决方案
正则表达式无法进行深度括号匹配。
如果你有一个固定的模式,你可以做到这一点——比如三个深括号,以及顶层括号中的第二组兄弟,依此类推。但是仅使用正则表达式将任意右括号与左括号匹配并不容易(如果有一种实用的方法可以使用正则表达式)。
编写几行 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)']
推荐阅读
- python - 我正在尝试在函数错误的 tk 窗口中添加图像:-图像“pyimage4”不存在
- r - unmarshal failed: Near line 0 (last key parsed ''): bare keys cannot contain ':' in Rmarkdown blogdown with Hugo
- python - 如何用另一列中的值注释条形图
- case - VHDL:使用不关心是否正确?
- javascript - next.js 通过 babel 导入 svg 不缩放
- python - 基于用户选择的标签组合框状态
- firebase - 云 Firestore 中的时间字段 serverTimestamp() 在第一个快照上返回 null
- django - 如何制作`
`显示:换行过滤器后内联?
- vue.js - 为什么内容里面的v-card有点卡出来了?
- python - 使用 Google Cloud SDK 在本地运行的 Google Speech-to-Text JupyterLab 笔记本脚本