python正则表达式直到第一组数字

2024-05-16 18:46:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下文字:

Coast Repair,* Norfolk, Virginia, is awarded a not-to-exceed $212,967,725 firm-fixed-price, indefinite-delivery/indefinite-quantity (IDIQ) multiple award contract (MAC) for ship repair, maintenance, and modernization of surface combatants (DDG and CG) class ships and amphibious (LSD, LPD and LHD) class ships homeported in Mayport, Florida, under Lot 1.  This award was made under rolling admissions of the current IDIQ-MAC Lot 1.  This contract includes options which, if exercised, would bring the cumulative value of this contract to $376,964,825.

我试图捕获第一个逗号,第二个逗号,第三个逗号左边的文本,以及$212967725

到目前为止,我的正则表达式是:(.*)(?:, )(?:.*)(?:\$([0-9,]+)

然而,这是捕捉几乎所有与该表达式匹配的内容。有没有一种方法或标志可以在捕获最后一组数字后停止匹配,然后出现空格

所以我的最终目标是:

('Coast Repair,* Norfolk, Virginia', '212,967,725')

Tags: andoftomacclass逗号contractrepair
2条回答

采取两步方法:

  • 查找数量前的文本(直到第一个$字符组#1) 以及数量本身(第2组)
  • 将组#1除以逗号

因此,第一步要使用的模式是:

pat1 = re.compile(r'^([^$]+)(\$[\d,]+)')

然后使用以下模式:

m = pat1.search(txt)

并保存两个捕获组:

g1 = m.group(1)
g2 = m.group(2)

然后在每个逗号前找到部分文本(步骤2):

g1.split(',')

获取:

['Coast Repair', '* Norfolk', ' Virginia', ' is awarded a not-to-exceed ']

(第一个逗号(Coast Repair)前的文本,第二个逗号(* Norfolk), 第三个逗号(Virginia),最后在数量之前 (is awarded a not-to-exceed

当然,数量是在g2变量中,所以您也可以打印它

与其尝试捕获特定数量的逗号,不如尝试使用正则表达式来获取“0-9字符串前的最后一个逗号之前的所有内容”。正则表达式应该是

([^$]*),.*?\$([0-9,]+)

所以基本上,一步一步

  • ([^$]*)捕获每个非$字符^{<重要的是让事物停在第一个美元符号而不是最后一个美元符号
  • \$([0-9,]+)用逗号捕捉一个数字,前面紧跟一个美元符号
  • ,.*?有效地匹配美元符号前面的最后一个逗号,然后懒洋洋地吃掉逗号和第一个美元符号之间的所有字符

Here's a regex101 link to show it works

相关问题 更多 >