正则表达式中,\d和[0-9]都用于匹配数字
区别在于:\d的匹配范围比[0-9]更广泛
例如:中文输入法输入全角数字,\d能匹配而[0-9]不能
Python代码示例
import re
a = '1234567890'
print(re.findall('[0-9]', a))
print(re.findall('[0-9]', a))
print(re.findall('\d', a))
打印结果
[]
['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
时间测试
[0-9]范围更小,因此速度更快
from re import search
from time import time
a = 'abcde' * 99
t0 = time()
[search('[0-9]', a) for _ in range(999999)]
t1 = time()
[search('\d', a) for _ in range(999999)]
t2 = time()
print('时间测试结果', t1 - t0, t2 - t1)
时间测试结果 3.1126251220703125 5.270697116851807
本文详细对比了正则表达式中d与[0-9]的区别,解释了d为何能匹配更多类型的数字,包括中文全角数字,并通过Python代码示例验证了这一特性。同时,文章还提供了时间测试结果,比较了两种表达式的运行效率。
680

被折叠的 条评论
为什么被折叠?



