You were matching the entire string and replacing it, use a lookahead and only match the whitespace and (1)
before the final extension.
Expanded RegEx:
\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)
Demo: Regex101
Implementation:
pattern = '\s*\([0-9]+\)(?=\.mp3$)'
processed = re.sub(pattern, '', string)
Notes:
mp3
can be replaced by[^.]+
to match any extension or(mp3|mp4)
to match multiple extensions.- use
\s+
instead of\s*
to require at least some whitespace before(1)
, thanks @SethMMorton.