在Python中使用正则表达式查找字符串中的所有数字

在Python数据分析中,仅从文本中提取数字是非常普遍的要求。使用python正则表达式库可以轻松完成此操作。这个库帮助我们定义数字的模式,这些模式可以提取为子字符串。

例子

在下面的示例中,我们使用findall()re模块中的函数。这些函数的参数是我们要提取的模式和我们要提取的字符串。请注意,在下面的示例中,我们仅得到数字,而没有小数点或负号。

import re
str=input("Enter a String with numbers: \n")
#Create a list to hold the numbers
num_list = re.findall(r'\d+', str)
print(num_list)

输出结果

运行上面的代码给我们以下结果-

Enter a String with numbers:
Go to 13.8 miles and then -4.112 miles.
['13', '8', '4', '112']

捕获小数点和符号

我们可以扩展搜索模式以在搜索结果中也包含小数点和负号或正号。

例子

import re
str=input("Enter a String with numbers: \n")
#Create a list to hold the numbers
num_list=re.findall(r'[-+]?[.]?[\d]+',str)
print(num_list)

输出结果

运行上面的代码给我们以下结果-

Enter a String with numbers:
Go to 13.8 miles and then -4.112 miles.
['13', '.8', '-4', '.112']