正则表达式中*的疑问

import re
text = 'thenextnothingis123456'
print(re.search(r'(\d*)', text).group(0))

为什么这段代码不能匹配出数字?如果将d替换成w反倒可以匹配出所有字符?

倚天杖
浏览 574回答 6
6回答

当年话下

>>> 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

大话西游666

你试试\d,另外*是表示0次或多次

aluckdog

>>> import re >>> text = 'thenextnothingis123456' >>> print(re.search(r'(\d+)', text).group(0)) 123456 >>> 可以用(\d+)规则匹配~ 同问为什么r'(\d*)无法匹配出字符串"123456"?
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python