Python 使用正则表达式从字符串中提取所有数字
在 Python 中,我们可以使用 re 模块来处理正则表达式。要从字符串中提取所有数字,可以使用 re.findall() 函数,它能够返回所有匹配正则表达式的子串。
实例
import re
# 示例字符串
text = "The price is 45 dollars and 30 cents."
# 使用正则表达式提取所有数字
numbers = re.findall(r'd+', text)
print(numbers)
# 示例字符串
text = "The price is 45 dollars and 30 cents."
# 使用正则表达式提取所有数字
numbers = re.findall(r'd+', text)
print(numbers)
代码解析:
import re:导入 Python 的正则表达式模块。text = "The price is 45 dollars and 30 cents.":定义一个包含数字的字符串。re.findall(r'd+', text):使用re.findall()函数来查找字符串中所有匹配正则表达式d+的子串。d+表示匹配一个或多个连续的数字。print(numbers):输出提取到的所有数字。
输出结果:
['45', '30']

Python3 实例