如何在Python中获取多个正则匹配?
我有这段文本:
<div class="additional-details">
<div class="mark-container">
<input type="checkbox" id="comp-80174649" value="80174649"
data-heading-code="2550"/>
<label for="comp-80174649">???</label>
<a href="#" class="compare-link" id="compare-link-1"
data-compare="/80174649/2550/"
data-drop-down-id="compare-content-1"
data-drop-down-content-id="compare-content"
data-drop-down-class="drop-down-compare"
etc...
data-compare="/8131239/2550/"
我想提取 data-compare="HERE" 里面的内容(我有多个匹配项)。
我知道怎么在 C# 中做到这一点,使用 MatchCollection,但在 Python 中,我对 re.search、re.match 感到很困惑,而且我发现 C# 中有效的正则表达式在 Python 中并不太管用。
有人能解释一下怎么做吗?
1 个回答
1
re.findall
可以用来在一个列表中找到所有匹配的内容。
>>> import re
>>> s = '<div cla' # whole string here
>>> result = re.findall('data-compare="([\d/]+)"', s)
>>> print result
['/80174649/2550/', '/8131239/2550/']
解释
我们想要的输出像 '/80174649/2550/'
这样的字符串,里面只有数字和斜杠,所以我们只关注这些部分。
在 ([\d/]+)
中,[\d/]
的意思是匹配一个数字(用 \d
表示)或者一个斜杠 /
。
然后 +
符号表示前面的模式 [\d/]
可以出现多次,因为我们确实有多个数字和 /
。
外面的括号表示我们只想捕捉并返回里面的模式 [\d/]+
。