用于提取字符串中数字的python正则表达式

2024-04-30 06:14:32 发布

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

我的字符串是:

<tr id="xyz21" style="" class="standard">

当我通过在线regex助手网站运行regex时,pythex.org网站,我得到了我想要的;只有数字“21”。网站上说:

匹配捕获“21”

下面是我使用的正则表达式:

<tr id="xyz(.*?)"

然而,当我在python3脚本中使用相同的正则表达式时,我得到的要多得多。下面是脚本和结果:

>>> import re
>>> x = '<tr id="xyz21" style="" class="standard">'
>>> num = re.search('<tr id="xyz(.*?)"', x).group()
>>> print(num)
<tr id="xyz21"

最后,我只想创建一个值为“21”的变量。顺便说一下,我使用regex的实际字符串比我显示的要长得多。实际上,这是一个小文件。我简化了我的例子,只是为了让它更容易理解。有什么想法吗?你知道吗


Tags: 字符串re脚本id网站style助手num
1条回答
网友
1楼 · 发布于 2024-04-30 06:14:32

您需要添加一个参数:

re.search('<tr id="xyz(.*?)"', x).group(1)

报告指出

If there is a single argument, the result is a single string; if there are multiple arguments, the result is a tuple with one item per argument. Without arguments, group1 defaults to zero (the whole match is returned). If a groupN argument is zero, the corresponding return value is the entire matching string; if it is in the inclusive range [1..99], it is the string matching the corresponding parenthesized group.

相关问题 更多 >