python - 正则表达式查找嵌套括号之间的文本

标签 python regex

我有一个很长的字符串,其中有嵌套循环。我想从中提取一个模式。

String_Text:

some random texts......
........................
........................
{{info .................
.....texts..............
...{{ some text }}...... // nested parenthesis 1
........................
...{{ some text }}...... // nested parenthesis 2
........................
}} // End of topmost parenthesis
........................
..again some random text
........................
........................ // can also contain {{  }}
......End of string.

我想提取最上面括号之间的所有文本,即

提取的字符串:

info .................
.....texts..............
...{{ some text }}...... // nested parenthesis 1
........................
...{{ some text }}...... // nested parenthesis 2
........................

图案:

1.) starts with { and can be followed by any number of {.

2.) After that there can be any number of white space.

3.) The first word after that is surely info.

4.) Extract till this bracket is not closed.

到目前为止尝试了什么:

re.findall(r'\{+[^\S\r\n]*info\s*(.*(?:\r?\n.*)*)\}+')

我知道这是错误的,因为这是在字符串中找到 的最后一个实例。有人可以帮我提取这些括号之间的文字吗?时间差

最佳答案

您需要使用递归方法:

{
    ((?:[^{}]|(?R))*)
}

只有较新的 regex 模块支持,参见 a demo on regex101.com .

关于python - 正则表达式查找嵌套括号之间的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51965650/

相关文章:

python - 如何使用 Music21 检索钢琴曲的左手和右手

python - Odoo 10 - 将订单行树字段添加到自定义模块

python - 无法解决问题: unsupported operand type(s) for -: 'dict' and 'set'

用于验证 192.169.0.0/24 等模式的 Javascript 正则表达式

python - 将文本拆分到关联表时无法显示文本列

regex - .gitignore 文件不在一个集合中

regex - 为什么空格分隔而不是 FPAT

c# - 大于零的十进制验证

Python正则表达式替换

python - 在 QtableView 中不可编辑的单元格上按 Tab 键