python - 找到两组交替出现重叠的字符串之间的字符串
问题描述
我有一些字符串看起来像:
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]
我想匹配前 3 个字符串中的金额 $12000、$10000、10000 以及最后一个字符串中的 $10000 和 $9000.00。但是,在第一个字符串中同时存在“价格”和“金额”。我想通过使用“|” 正则表达式将从左到右搜索,所以我希望正则表达式首先查看“金额”,如果没有出现,则查找“价格”。我尝试了以下代码:
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_p = re.compile(r'.*(?:amount|price):(.*?)(?:USD|\.00)')
这给了我
['12000']
['10000']
[' 10000 ']
['$9000']
在这种情况下,正则表达式仅匹配最后一个字符串中的 $9000 并忽略 $10000。所以我的问题是 .* 一开始的功能是什么,有没有办法解决我的问题?查找数字不起作用,因为在我的实际数据中,一个文本中有许多其他数字。谢谢大家!!!!
解决方案
第一条语句:
amount_p = re.compile(r'(?:amount|price):(.*?)(?:USD|\.00)')
您没有按照您的意图正确分组字符串(我相信您的意思是按“:”分组),所以您仍然让您的字符串作为一个存在。你只能在 str2 和 str3 中得到你的数字,因为'.USD' and '.00'
你来了。
使用第二个语句:
amount_p = re.compile(r'.*(?:amount|price):(.*?)(?:USD|\.00)')
您可以使用“:”正确拆分字符串。因此,str1 看起来像:
第1部分:“数量和价格”和第2部分:“120个;总金额:12000.00”
所以你能够提取你的价值观。您可以将其视为执行以下操作:
strlist=[str1.split(';')[1],str2,str3,str4]
当与您的第一个模式结合使用时,会产生与第二个相同的结果
参考:https ://www.tutorialspoint.com/python/python_reg_expressions.htm
推荐阅读
- memory - 我可以给malloc映射内存吗?
- python - 相当于 pandas.DataFrame 的 pandas.Series.value_counts
- mysql - 同一属性有多种可能的数据类型:空条目、EAV 或存储为 varchar?
- c++ - 在 wxWidgets 中绘制图像/矩阵
- kendo-ui - KendoUI 计算 observable
- python - 截断数据框的字符串并将它们组合在一起
- c++ - 菜鸟问题:试图审查向量中的特定单词
- prometheus-alertmanager - 如何修复'err="yaml: unmarshal errors:\n line 21: field routes not found in type config.plain"'
- android - Travis 和 React Native。Parallels 为 Android 和 ios 构建
- java - 如何在 Android 项目中使用 JDK 12