正则表达式在子字符串之前捕获所有

时间:2018-07-03 11:32:29

标签: python regex

我有一个字符串:

s = 'Abc - 33 SR 11 Kill(s) P G - (Type-1P-G) 2 Kill(s) M 1 Kill(s) S - M9A CWS 1 Kill(s) 11 Kill(s)'

我正试图将其拆分以捕获杀戮次数,以及每个"XY Kill(s)"之前的信息以获取此输出:

['Abc - 33 SR', 
 'P G - (Type-1P-G)', 
 'M', 
 'S - M9A CWS']

获得杀死人数很简单:

re.findall(r"(\d+) Kill", s)
['11', '2', '1', '1', '11']

获取文字更加困难。通过研究,我尝试使用以下正则表达式,该正则表达式只是一系列捕获组的开始:

re.findall(r"(?=[0-9]+ Kill)", s)
['', '', '', '', '', '', '']

然后我将其更改为在“每组之前添加任意数量的字符”。

re.findall(r"(.+)(?=[0-9]+ Kill)", s)
['Abc - 33 SR 11 Kill(s) P G - (Type-1P-G) 2 Kill(s) M 1 Kill(s) S - M9A CWS 1 Kill(s) 1']

这只是给出了整个字符串。我该如何调整它以捕获“任意数量的数字-空格-杀死”之前的所有内容?

让我们摆脱困境。我已经咨询了以下内容。特别是第二个看起来有用,但我一直无法使其达到这个目的。

Extract Number before a Character in a String Using Python

How would I get everything before a : in a string Python

how to get the last part of a string before a certain character?

2 个答案:

答案 0 :(得分:1)

您可以使用

re.findall(r'(.*?)\s*(\d+) Kill\(s\)\s*', s)

请参见regex demo

详细信息

  • (.*?)-捕获组1:除换行符以外的任何0+个字符,并且尽可能少
  • \s*-超过0个空格
  • (\d+)-捕获第2组:一个或多个数字
  • Kill(s)-一个空格和Kill(s)子字符串
  • \s*-超过0个空格

Python demo

import re
rx = r"(.*?)\s*(\d+) Kill\(s\)\s*"
s = "Abc - 33 SR 11 Kill(s) P G - (Type-1P-G) 2 Kill(s) M 1 Kill(s) S - M9A CWS 1 Kill(s) 11 Kill(s)"
print(re.findall(rx, s))

输出:

[('Abc - 33 SR', '11'), ('P G - (Type-1P-G)', '2'), ('M', '1'), ('S - M9A CWS', '1'), ('', '11')]

答案 1 :(得分:1)

您可以使用re.split()来获取匹配范围 中所有内容的列表。

Route for Vehicle1
[LOCATION, START, CAPACITY]
['Depot', '4:0', 0]
[u'Location1', '9:0', 1]
[u'Location2', '10:0', 4]
['Depot', '11:00', 0]
[u'Location3', '12:0', 1]
[u'Location4', '13:0', 2]
[u'Location5', '14:0', 4]
['Depot', '15:00', 0]

您可以清理它以删除空格和空字符串。

>>> re.split(r"\d+ Kill\(s\)", s)
    ['Abc - 33 SR ', ' P G - (Type-1P-G) ', ' M ', ' S - M9A CWS ', ' ', '']
相关问题