import re
text = 'thenextnothingis123456'
print(re.search(r'(\d*)', text).group(0))
为什么这段代码不能匹配出数字?如果将d替换成w反倒可以匹配出所有字符?
6 回答
当年话下
TA贡献1890条经验 获得超9个赞
>>> print(re.search(r'(\d*)', "abcd1234").group(0)) ########11111111
>>> print(re.search(r'(\d*)', "1234abcd").group(0))
1234
>>> print(re.search(r'[a-z]*(\d*)', "abcd1234").group(1))
1234
>>> print(re.search(r'(\d{0})', "abcd1234").group(0)) #######2222222
>>> print(re.search(r'(\d+)', "abcd1234xxx4321").group(0))
1234
>>> print(re.search(r'(\d+)', "abcd1234xxx4321").group(1)) ####可见re.search第一次匹配成功后就不再接着匹配
1234
>>> print(re.search(r'(\d+)', "abcd1234xxx4321").group(2))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: no such group
11111111这一句之所以结果为空,是由于re.search用了#######2222222
aluckdog
TA贡献1847条经验 获得超7个赞
>>> import re
>>> text = 'thenextnothingis123456'
>>> print(re.search(r'(\d+)', text).group(0))
123456
>>>
可以用(\d+)规则匹配~
同问为什么r'(\d*)无法匹配出字符串"123456"?
添加回答
举报
0/150
提交
取消