gpt4 book ai didi

python - 正则表达式捕获子字符串之前的所有内容

转载 作者:行者123 更新时间:2023-12-01 01:47:17 25 4
gpt4 key购买 nike

我有一个字符串:

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?

最佳答案

您可以使用

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

关于python - 正则表达式捕获子字符串之前的所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51153569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com