匹配 数字三连....
import re
s = 'abc 456 def'
re.search('\d\d\d', s) # 成功
re.search('\d{3}', s) # None
re.search('[0-9]{3}', s) # 成功
为什么 \d{3}
不行, 我在在线正则测试的工具网站上试过 \d{3}
并没有错, google 也没找到有说明的, 可能是关键字不对
1
oldshensheep 2021-05-09 12:44:23 +08:00
|
2
Trim21 2021-05-09 12:47:21 +08:00 via Android
试了试第二个能正确匹配
|
3
cherbim 2021-05-09 13:06:38 +08:00 via iPhone
我测试第二个成功啊
|
4
ClericPy 2021-05-09 13:52:37 +08:00
python 3.7 3.8 3.9 2.7 都能正确匹配
要不你试试 r'\d{3}' |
5
iptables 2021-05-09 13:56:46 +08:00
我的测试结果
$ python3.9 Python 3.9.5 (default, May 3 2021, 19:12:05) [Clang 12.0.5 (clang-1205.0.22.9)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> >>> import re >>> >>> s = 'abc 456 def' >>> >>> re.search('\d\d\d', s) <re.Match object; span=(4, 7), match='456'> >>> re.search('\d{3}', s) <re.Match object; span=(4, 7), match='456'> >>> re.search('[0-9]{3}', s) <re.Match object; span=(4, 7), match='456'> >>> >>> re.search(r'\d\d\d', s) <re.Match object; span=(4, 7), match='456'> >>> re.search(r'\d{3}', s) <re.Match object; span=(4, 7), match='456'> >>> re.search(r'[0-9]{3}', s) <re.Match object; span=(4, 7), match='456'> >>> |
6
plko345 OP |
7
crystom 2021-05-09 14:25:21 +08:00 3
python3 的\d 包括各种 unicode 数字,不光是 0-9
|