我有一些类似于以下字符串:
str1="Quantity and price: 120 units;the total amount:12000.00"
str2="Quantity:100, amount:10000.00"
str3="Quantity:100, price: 10000 USD"
str4="Parcel A: Quantity:100, amount:$10000.00,Parcel B: Quantity:90, amount:$9000.00"
strlist=[str1,str2,str3,str4]
我想在前三个字符串中匹配金额为$12000,$10000和10000,并且在最后一个字符串中匹配$10000和$9000.00。然而,在第一个字符串中既有“price”又有“amount”。我认为使用“|”正则表达式会从左到右搜索,因此我希望正则表达式首先查找“amount”,如果没有出现,则查找“price”。我尝试了以下代码:
amount_p = re.compile(r'(?:amount|price):(.*?)(?:USD|\.00)')
for i in strlist:
amount=re.findall(amount_p,i)
print(amount)
[' 120 units;the total amount:$12000']
['10000']
[' 10000 ']
['$10000', '$9000']
一些方法可以忽略“amount”,仅在第一个字符串中查找“price”。然后我尝试了以下操作:
amount_p = re.compile(r'.*(?:amount|price):(.*?)(?:USD|\.00)')
这使我
['12000']
['10000']
[' 10000 ']
['$9000']
在这种情况下,正则表达式只匹配了最后一个字符串中的 $9000,并忽略了 $10000。那么我的问题是,.* 在开头的作用是什么,有没有办法解决我的问题?查找数字行不通,因为在我的实际数据中,一段文本中有许多其他数字。 提前感谢大家!
re.findall(r'(?:price|amount):\s*\$?(\d+)(?:\.\d+|\s*USD)', text)
进行匹配(演示) - Wiktor Stribiżew