代码示例:
import re
input_str = "I bought 5 kg of apples and 2 lbs of bananas"
weight_pattern = r"\d+\s*(kg|lbs)"
weights = re.findall(weight_pattern, input_str)
print("Weights found in input string:")
for weight in weights:
print(weight)
解释:
该程序首先使用re模块中的findall()方法搜索输入字符串中匹配指定正则表达式模式的所有重量值。 正则表达式模式使用\d+匹配一个或多个数字,接着使用\s*匹配可能存在的空格,最后是kg或lbs,匹配单位kg或lbs之一。
然后,将所有匹配的重量值打印到控制台上。在此示例中,程序将打印“5 kg”和“2 lbs”。