Python正则表达式生成单词,直到找到字符或特殊单词为止

2024-04-24 07:04:14 发布

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

几个小时来我一直在努力解决这个问题,只是因为某些原因,我似乎无法理解regex

我用这个模式逐行查看下面的字符串:

pattern = re.compile(r"^[^&,]*")

字符串保存在字典中,因此循环如下:

for dct in lst:
    print(re.search(pattern, dct['artist']).group(0))

"""
Drake
Post Malone Featuring Ty Dolla $ign
BlocBoy JB Featuring Drake
Offset & Metro Boomin
Jay Rock, Kendrick Lamar, Future & James Blake
"""

如上所述,我得到了预期的结果:

"""
Drake
Post Malone Featuring Ty Dolla $ign
BlockBoy JB Featuring Drake
Offset
Jay Rock 
"""

但是我不知道如何得到add,它也应该停在字符串“featured”上,我尝试了100种不同的\bfeature\b,capitalB,前面有不同的标记,后面有不同的标记,在regex中有不同的位置

这是我得到的最接近的,但它只匹配有“特色”的行:

pattern = re.compile(r"^[^&,]*(?=\bFeaturing\b)")

这给了我这个输出:

None
<_sre.SRE_Match object; span=(0, 12), match='Post Malone '>
<_sre.SRE_Match object; span=(0, 11), match='BlocBoy JB '>
None
<_sre.SRE_Match object; span=(0, 12), match='Post Malone '>
None

我对这一点还比较陌生,所以我所做的大部分工作都是反复尝试,但我几乎要放弃了。请帮我得到这样的结果:

"""
Drake
Post Malone
BlockBoy JB
Offset
Jay Rock 
"""

Tags: 字符串renonematchpostdrakeoffsetpattern
2条回答

你可以用

re.findall(r'^(?:(?!\bFeaturing\b)[^&,\n])*\b', s, re.M)

或者

re.findall(r'^.*?(?=\s*(?:\bFeaturing\b|[&,]|$))', s, re.M)

this regex demoanother one。就结果而言,regexp是等价的

细节

  • ^-行首
  • (?:(?!\bFeaturing\b)[^&,\n])*-(请参见more about this construct)除&,之外的任何字符,以及尽可能多的不以整个单词Featuring开头的换行符
  • \b-单词边界

  • .*?(?=\s*(?:\bFeaturing\b|[&,]|$))-匹配除换行符以外的任何0+字符,尽可能少(.*?)到最左边出现的0+空格,后跟

    • \bFeaturing\b-整词Featuring
    • [&,]-a &,字符
    • $-行尾

您可以使用re.sub

str = re.sub(r'\s*(?:[&,]|Featuring).*', '', str)

RegEx Demo

\s*(?:[&,]|Featuring).*将匹配任何一行中以&,Featuring开头的文本,直到行尾,我们将其替换为空字符串

相关问题 更多 >