首页 > 解决方案 > 如何懒惰地使用正则表达式匹配包含特定字符串的字符串?

问题描述

我想在 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

标签: regexpython-3.x

解决方案


事实证明,解决方案非常简单,这是有效的正则表达式:

.*(<([a-zA-Z0-9]+?)\b[^>]*>.*?<tag2>some other text</tag2>.*?</\2>).*


推荐阅读