Skip to main content
 首页 » 编程设计

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

2024年09月07日39lori

现在已经为此苦苦挣扎了几个小时,出于某种原因似乎无法理解正则表达式。

我正在使用这种模式逐行查看下面的字符串:

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  
""" 

但我不知道如何添加它也应该在字符串“Featuring”处停止,我尝试了 100 种不同的\bFeaturing\b 变体,大写 B,不同的标记在 regex 中的前面、后面、位置。

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

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  
""" 

请您参考如下方法:

你可以使用

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

或

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

参见 this regex demo或 another one .就结果而言,正则表达式是等效的。

详情

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

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

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