我想使用python正则表达式提取两个不同字符>和<之间的子字符串。这是我的示例字符串:<h4 id="Foobar:">Foobar:</h4><h1 id="Monty">Python<a href="https://..."></a></h1>我当前的正则表达式是\>(.*)\<和匹配:FoobarPython<a href="https://..."></a>我重新正确匹配第一个示例,但不匹配第二个示例。我希望它返回“ Python”。我想念什么?
2 回答
胡说叔叔
TA贡献1804条经验 获得超8个赞
使用表达式:
(?<=>)[^<:]+(?=:?<)
(?<=>)积极回首>。[^<:]+匹配<或以外的其他任何内容:。(?=:?<)积极向前展望可选冒号:,和<。
您可以在此处尝试使用该表达式。
在Python中:
import re
first_string = '<h4 id="Foobar:">Foobar:</h4>'
second_string = '<h1 id="Monty">Python<a href="https://..."></a></h1>'
print(re.findall(r'(?<=>)[^<:]+(?=:?<)',first_string)[0])
print(re.findall(r'(?<=>)[^<:]+(?=:?<)',second_string)[0])
印刷:
Foobar
Python
或者,您可以使用表达式:
(?<=>)[a-zA-Z]+(?=\W*<)
(?<=>)积极回首>。[a-zA-Z]+小写和大写字母。(?=\W*<)正向查找所有非单词字符,后跟<。
您可以在此处测试此表达式。
print(re.findall(r'(?<=>)[a-zA-Z]+(?=\W*<)',first_string)[0]) print(re.findall(r'(?<=>)[a-zA-Z]+(?=\W*<)',second_string)[0])
印刷:
Foobar Python
添加回答
举报
0/150
提交
取消
