python 正则表达式找出字符串中的纯数字

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012111465/article/details/82826884

1、简单的做法

>>> import re
>>> re.findall(r'\d+', 'hello 42 I'm a 32 string 30')
['42', '32', '30']

然而,这种做法使得字符串中非纯数字也会识别

>>> re.findall(r'\d+', "hello 42 I'm a 32 str12312ing 30")
['42', '32', '12312', '30']

2、识别纯数字

如果只需要用单词边界( 空格句号逗号) 分隔的数字,你可以使用 \b

>>> re.findall(r'\b\d+\b', "hello 42 I'm a 32 str12312ing 30")
['42', '32', '30']
>>> re.findall(r'\b\d+\b', "hello,42 I'm a 32 str12312ing 30")
['42', '32', '30']
>>> re.findall(r'\b\d+\b', "hello,42 I'm a 32 str 12312ing 30")
['42', '32', '30']

猜你喜欢

转载自blog.csdn.net/u012111465/article/details/82826884