regex - 如何懒惰地使用正则表达式匹配包含特定字符串的字符串?
问题描述
我想在 python 中使用正则表达式匹配一个字符串,其中包含一个特定的字符串(惰性匹配),但还没有弄清楚如何去做。
例如,在下面的示例中,我如何只返回'<tag1>some text<tag2>some other text</tag2><tag1>'
而不是整个字符串
#!/bin/python3
import re
pattern = r'(<([a-zA-Z0-9]+?)\b[^>]*>.*?<tag2>some other text</tag2>.*?</\2>)'
text = '<root> <tag1>some text<tag2>some other text</tag2></tag1> </root>'
print(re.search(pattern, text, re.DOTALL).groups(0))
上面的代码<root> <tag1>some text<tag2>some other text</tag2></tag1> </root>
在我希望打印时打印<tag1>some text<tag2>some other text</tag2></tag1>
当然,所有这些都假设可以有任何标签代替tag1
解决方案
事实证明,解决方案非常简单,这是有效的正则表达式:
.*(<([a-zA-Z0-9]+?)\b[^>]*>.*?<tag2>some other text</tag2>.*?</\2>).*
推荐阅读
- json - 如何访问嵌套的 json 数据?
- java - Java 8 到 Kava 11 的迁移问题
- php - 刀片文件中的 Laravel 双插值
- html - 换行后对齐文本不起作用
- javascript - 什么是针对使用 JavaScript 克隆的 html 输入的方法
- validation - 为什么验证损失增加或略有变化?
- python - Python 上的 TouchAction 是否比 Appium 检查器上的按下时间更长?
- python - 在 razorpay 中创建计划不支持美元
- python - Linux 上的 xlwings 替代方案
- reactjs - 在钩子中处理 setState 后的回调函数