使用正则表达式捕获特定数字的方法取决于具体的需求。以下是几个常见的示例:
import re
text = "I have 10 apples and 20 oranges."
matches = re.findall(r'\d+', text) # 使用\d+匹配一个或多个数字
print(matches) # 输出: ['10', '20']
import re
text = "The price is $9.99."
matches = re.findall(r'\d+\.\d+', text) # 使用\d+\.\d+匹配一个或多个数字和小数点
print(matches) # 输出: ['9.99']
import re
text = "The numbers are 5, 10, 15, and 20."
matches = re.findall(r'[5-9]|[1-2][0-9]', text) # 使用[5-9]|[1-2][0-9]匹配5到9或10到29之间的数字
print(matches) # 输出: ['5', '10', '15', '20']
这些示例仅为了说明如何使用正则表达式捕获特定数字,并且具体的正则表达式模式可能会因需求而有所不同。您可以根据实际情况修改正则表达式模式以满足您的需求。
下一篇:捕获特定异常