python - 正则表达式匹配最后的模式

标签 python regex

嗨,我陷入了提取数据的困境,

import re
s = "this is the [[sample1]] string [[sample2]](explanation)"
re.findall("(?=\[\[)(.*)(?<=\))",s)

此结果:['[[sample1]] string [[sample2]](explanation)']

但我想提取:[[sample2]](explanation)']

请建议一种方法来做到这一点。

提前致谢!

最佳答案

这个表达式也可能有效:

(\[\[[^\]]*\]\]\([^)]*\))

使用re.findall进行测试

import re

regex = r"(\[\[[^\]]*\]\]\([^)]*\))"

test_str = """

this is the [[sample1]] string [[sample1]](explanation) this is the [[sample1]] string 

[[sample2]](explanation1) [[]]()

[[sample3]](explanation1) [[sample4]]()

"""


print(re.findall(regex, test_str, re.M))

输出

['[[sample1]](explanation)', '[[sample2]](explanation1)', '[[]]()', '[[sample3]](explanation1)', '[[sample4]]()']

该表达式在 regex101.com 的右上角面板中进行了解释,如果您想探索/简化/修改它,请在this link中,如果您愿意,您可以观察它如何与某些示例输入匹配。

正则表达式电路

jex.im可视化正则表达式:

enter image description here

关于python - 正则表达式匹配最后的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57136518/

相关文章:

c# - 正则表达式可以匹配交错匹配吗?

python - 加减

python - 通过 PATCH : how to parse JSON data for SQL updates? 进行部分更新

python - 有没有一种更优雅的方法可以将字典的键和值解包到两个列表中,而又不会失去一致性?

Python 正则表达式获取两个子字符串之间的字符串

javascript - 如何调整谷歌地图的宽度和高度

regex - 在 Powershell 中使用正则表达式抓取电子邮件

python - 如何在 python 中使用枚举?

python - Django 独立脚本

Javascript RegExp 在 IE 中不起作用