用Python搜索模式会在regex101中返回2组,但在Python中会返回1组[duplicate]

问题描述 投票:-1回答:1

我想捕获短语“特殊代码”后面的数字,并返回其开始索引和结束索引。

这是一个示例:

    text = "The special code is 034567 in this particular case and not 98675.  But the special code 67869 would be correct"

我的代码如下:

text = "The special code is 034567 in this particular case and not 98675.  But the special code 67869 would be correct"

p = re.compile('special\scode\s(?:\w*\s)?(\d+)')

m = re.search(p, text)

m.group(1)

'034567'

m.group(2)

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-130-88acecccb001> in <module>
----> 1 m.group(2)

IndexError: no such group

此代码返回仅捕获了一个组的对象。

但是在regex101中测试时,相同的regex表达式会捕获两个数字。

https://regex101.com/r/jyVI5q/1

enter image description here

您能帮助我理解为什么以及应该做什么吗?

python-3.x regex search re regex101
1个回答
-1
投票

the official documentationre.search返回“正则表达式pattern产生匹配的first位置”。

您想在这里使用re.findall(不需要re.findall):

group

结果:

import re
text = "The special code is 034567 in this particular case and not 98675.  But the special code 67869 would be correct"

p = re.compile('special\scode\s(?:\w*\s)?(\d+)')

m = re.findall(p, text)
print (m)
© www.soinside.com 2019 - 2024. All rights reserved.