使用正则表达式从短HTML片段中提取一些数字

2024-06-28 11:32:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个像下面这样的字符串,我想得到两个数字“28”和“1”,但现在我只能通过我的代码得到“28”。请帮帮我。你知道吗

import re
content="""<span class="lineNum">      28 </span><span class="lineCov">          1 : get_pid_file(const char *file, pid_t *pid)</span>"""
pattern = "(\d+)"
ret = re.search(pattern,content)
if ret:
   print "find: %s" % ret.group()

Tags: 字符串代码importre数字contentpidclass
2条回答

使用^{}

>>> re.findall(r"\d+", content)
['28', '1']

但你可能想缩小你的正则表达式。你知道吗

编辑:

您可能需要将正则表达式更改为r"<span.*?>.*?(\d+).*?</span>"的某种变体,以便只匹配span标记中的数字。你知道吗

pattern = "(\d+).*(\d+)"
ret = re.search(pattern,content)
print ret.group(1), ret.group(2)

相关问题 更多 >