Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在发生重叠的两组交替字符串之间查找字符串_Python_Regex - Fatal编程技术网

Python 在发生重叠的两组交替字符串之间查找字符串

Python 在发生重叠的两组交替字符串之间查找字符串,python,regex,Python,Regex,我有一些字符串看起来像: 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: Quantit

我有一些字符串看起来像:

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']
在本例中,regex只匹配最后一个字符串中的$9000,而忽略了$10000。所以我的问题是。*一开始的作用是什么,有没有办法解决我的问题?寻找数字不起作用,因为在我的实际数据中,一个文本中有许多其他数字。
提前谢谢大家

第一句话:

amount_p = re.compile(r'(?:amount|price):(.*?)(?:USD|\.00)')
amount_p = re.compile(r'.*(?:amount|price):(.*?)(?:USD|\.00)')
您没有按照预期正确地对字符串进行分组(我相信您是按照“:”进行分组的),因此您仍然将字符串作为一个整体存在。您只能在str2和str3中得到您的数据,因为
“.USD”和“.00”
帮助了您

第二项声明如下:

amount_p = re.compile(r'(?:amount|price):(.*?)(?:USD|\.00)')
amount_p = re.compile(r'.*(?:amount|price):(.*?)(?:USD|\.00)')
您可以使用“:”正确拆分字符串。因此,str1-one看起来像:

第1部分:“数量和价格” 和 第2部分:“120个单位;总金额:12000.00”

所以你可以提取你的价值观。 您可以将其视为执行以下操作:

strlist=[str1.split(';')[1],str2,str3,str4]
当与第一种模式结合时,会产生与第二种模式相同的结果

参考资料:

您可以使用

re.findall(r'(?:price|amount):\s*\$?(\d+)(?:\.\d+|\s*USD)', text)

详细信息

  • (?:价格|金额)
    -
    价格
    金额
  • -冒号
  • \s*
    -0+空格
  • \$?
    -可选的美元符号
  • (\d+)
    -第1组:一个或多个数字
  • (?:\.\d+\s*USD)
    ——一个非捕获组,匹配
    和1+数字或0+空格,然后再匹配
    USD
    子字符串

试试
re.findall(r'(?:价格|金额):\s*\$(\d+(:\.\d+\s*美元),text)
()非常感谢!它的工作和网站是真的有用很高兴为你工作。另外,如果我的回答对您有帮助(请参阅),因为您在达到15个代表点后有权享有向上投票的特权。注意:你可以投票选出所有有帮助的答案。