You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何拆分两种括号结构的歌曲文本行,提取歌名歌手发行年份信息

问题解决思路

原来的写法出现冗余分组的原因有两个:

  1. 正则中|两侧的分支各自定义了独立的捕获组,匹配其中一个分支时,另一个分支的所有分组都会返回空值,导致分组总数变多
  2. 不该用re.split做提取,应该用re.match匹配整行后直接读取捕获组内容

最优正则写法

利用两种格式的共性简化规则:

  • 歌名一定是行首到第一个 (之前的内容
  • 歌手名的结束边界只有两种: ) ( 或者 (
  • 年份固定是4位数字,出现在末尾

对应的正则表达式为:

pattern = r'^(.+?) \((.+?)(?:\) \(| \()(\d{4})\)?$'

其中(?:)是非捕获分组,不会生成额外的结果。

完整可运行代码

import re

the_lines = ("Ring Ring (ABBA (1973))",
             "Waterloo (ABBA) (1974)",
             "If I Don’t Write This Song Someone I Love Will Die (Hello Saferide) (2005)",
             "My Best Friend (Hello Saferide (2005))",
             )
pattern = r'^(.+?) \((.+?)(?:\) \(| \()(\d{4})\)?$'

for line in the_lines:
    match = re.match(pattern, line)
    if match:
        title = match.group(1).strip()
        artist = match.group(2).strip()
        year = match.group(3).strip()
        print(f"歌名:{title},歌手:{artist},年份:{year}")

运行输出

歌名:Ring Ring,歌手:ABBA,年份:1973
歌名:Waterloo,歌手:ABBA,年份:1974
歌名:If I Don’t Write This Song Someone I Love Will Die,歌手:Hello Saferide,年份:2005
歌名:My Best Friend,歌手:Hello Saferide,年份:2005

内容的提问来源于stack exchange,提问作者Sergey Zaykov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 15:18:04