【问题标题】:Regex capture all before substring正则表达式在子字符串之前捕获所有内容
【发布时间】:2018-12-11 17:00:10
【问题描述】:

我有一个字符串:

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']

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

让我们把受骗者排除在外。我咨询了以下内容。第二个看起来特别有用,但我无法使它适合这个目的。

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?

【问题讨论】:

标签: python regex


【解决方案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')]

【讨论】:

  • RegEx中也可以用\s+替换空格
  • @LaurentLAPORTE 嗯,这是原始模式的一部分,它是文字,所以我相信它是可以的。
【解决方案2】:

您可以使用re.split() 获取 个匹配项之间的所有内容列表。

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

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

>>> [s.strip() for s in re.split(r"\d+ Kill\(s\)", s) if s.strip()]
    ['Abc - 33 SR', 'P G - (Type-1P-G)', 'M', 'S - M9A CWS']

【讨论】:

    猜你喜欢
    • 2011-08-24
    • 1970-01-01
    • 2021-02-10
    • 2019-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-15
    • 1970-01-01
    相关资源
    最近更新 更多