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

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']
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章