代码举例:
import re
expression = "Price: $12,345.67"
# 数字放在括号中,以便能使用`group`将其提取出来,
pattern = 'Price: \$([0-9,]+\.[0-9]+)'
matches = re.search(pattern, expression)
entire_match = matches.group(0)
print(entire_match)
price = matches.group(1)
print("price_in_string: ", price)
# 如果字符串中存在逗号,需要将其删除,否则python无法将其转换成数字
print("price_in_float * 10 = ", float(price.replace(',', '')) * 10)
输出如下:
Price: $12,345.67
price_in_string: 12,345.67
price_in_float * 10 = 123456.7