我想捕获短语“特殊代码”后面的数字,并返回其开始索引和结束索引。
这是一个示例:
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
您能帮助我理解为什么以及应该做什么吗?
每the official documentation,re.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)