gpt4 book ai didi

Python正则表达式替换字符串

转载 作者:行者123 更新时间:2023-12-01 05:13:39 24 4
gpt4 key购买 nike

我正在努力实现以下目标:

string = 'C:/some path to mp3/song (7) title and so on (1).mp3'

应该变成:

C:/some path to mp3/song (7) title and so on.mp3

为了匹配它,我使用以下正则表达式:

pattern = '.*(\s\([0-9]+\))\.mp3'

匹配组包含:(u' (1)',)
但是,当我尝试像这样替换匹配时:

processed = re.sub(pattern, '', string)

processed 包含一个空字符串。我怎样才能让 re.sub() 只替换上面找到的匹配项?

最佳答案

您匹配整个字符串并替换它,使用前瞻并仅匹配空格和 (1)在最终扩展之前。

扩展正则表达式:

\s*     (?# 0+ characters of leading whitespace)
\( (?# match ( literally)
[0-9]+ (?# match 1+ digits)
\) (?# match ) literally)
(?= (?# start lookahead)
\. (?# match . literally)
mp3 (?# match the mp3 extension)
$ (?# match the end of the string)
) (?# end lookeahd)

演示: Regex101

实现:

pattern = '\s*\([0-9]+\)(?=\.mp3$)'
processed = re.sub(pattern, '', string)

注释:

  • mp3可以替换为[^.]+匹配任何扩展名或 (mp3|mp4)匹配多个扩展名。
  • 使用\s+而不是\s* (1) 之前至少需要一些空格,感谢@SethMMorton

关于Python正则表达式替换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23659174/

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