2

I am new to python and I have been searching for a method to replace a series of patterns and cannot find a method that uses regex, none of which I found have worked for me, here are some of my patterns and the code I am using:

regexes = {
    r'\s(\(|\[)(.*?)Mix(.*?)(\)|\])/i' : r"",
    r'\s(\(|\[)(.*?)Version(.*?)(\)|\])/i' : r"",
    r'\s(\(|\[)(.*?)Remix(.*?)(\)|\])/i' : r"",
    r'\s(\(|\[)(.*?)Extended(.*?)(\)|\])/i' : r"",
    r'\s\(remix\)/i' : r"",
    r'\s\(original\)/i' : r"",
    r'\s\(intro\)/i' : r"",
}

def multi_replace(dict, text):
    for key, value in dict.items():
        text = re.sub(key, value, text)
    return text

filename = "Testing (Intro)"

name = multi_replace(regexes, filename)

print(name)

I am pulling filenames from directories of music I own as I am a DJ, I belong to many record pools and they label their songs sometimes as follows;

SomeGuy - Song Name Here (Intro)

SomeGirl - Song Name Here (Remix)

SomeGirl - Song Name Here (Extended Version)

SomeGuy - Song Name Here (12" Mix Vocal)

and so on...

my regex above works in PHP in which it will remove all the values like (Intro) (Remix) (Extended Version), etc. so the output is;

SomeGuy - Song Name Here

SomeGirl - Song Name Here

SomeGirl - Song Name Here

SomeGuy - Song Name Here

and so on...

6
  • For doing a number of replacements, each of which has a different replacement value, your current approach is already fine. You could use a callback function, to perhaps use less code. Commented May 9, 2020 at 4:14
  • The problem is, it doesn't work, it doesn't replace the text.
    – DmVinny
    Commented May 9, 2020 at 4:25
  • Can you edit your question and make clear the search terms and replacements? Commented May 9, 2020 at 4:26
  • Edited, i think that is what you wanted.
    – DmVinny
    Commented May 9, 2020 at 4:31
  • Do you want to remove all values starting with '('? Commented May 9, 2020 at 4:45

1 Answer 1

1

For ignorecase you need to use re.I or re.IGNORECASE

Try with this code:

import re

regexes = {
    r'\s(\(|\[)(.*?)Mix(.*?)(\)|\])' : r"",
    r'\s(\(|\[)(.*?)Version(.*?)(\)|\])' : r"",
    r'\s(\(|\[)(.*?)Remix(.*?)(\)|\])' : r"",
    r'\s(\(|\[)(.*?)Extended(.*?)(\)|\])' : r"",
    r'\s\(remix\)' : r"",
    r'\s\(original\)' : r"",
    r'\s\(intro\)' : r"",
}

def multi_replace(dict, text):
    for key, value in dict.items():
        p = re.compile(key, re.I)
        text = p.sub(value, text)
    return text

filename = "Testing (Intro)"

name = multi_replace(regexes, filename)

print(name)
0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.