正则表达式\d和[0-9]的区别

正则表达式中,\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

猜你喜欢

转载自blog.csdn.net/Yellow_python/article/details/104997275