Single pass multiple re find and replace ignorecase

I would like to perform a single pass multiple find and replace but ignoring case. I have come across the below that works very well when accepting case sensitivity. Does anyone know how I would utilize a method such as below ignoring the case?

import re 

def multiple_replace(dict, text):
    regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
    return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text) 

if __name__ == "__main__": 

    text = "Test one, test One, test Two, tEst three"

    dict = {
      "Test one" : "Test 1",
      "Test Two" : "Test 2",
      "Test three" : "Test 3",

print multiple_replace(dict, text)

For example: In the above I would like to see all the keys get mapped to the values ignoring the keys case.

If anyone could point me in the right direction this would be appreciated

One thought on “Single pass multiple re find and replace ignorecase”

  1. You can use following function:
    def multiple_replace(my_dict, text):
    # first create a new dict by converting key values to lower case
    # this will help with the lookup later
    my_dict_lower = {k.lower(): v for k, v in my_dict.items()}

    # add re.IGNORECASE flag for case insenstivity
    regex = re.compile("(%s)" % "|".join(map(re.escape, my_dict_lower.keys())), re.IGNORECASE)

    # you can directly use to get the matched text.
    # convert it to lower case and get the value from dict to replace with.
    return regex.sub(lambda mo: my_dict_lower[], text)

    With the example above:
    >>> text = "Test one, test One, test Two, tEst three"
    >>> my_dict = {
    ... "Test one": "Test 1",
    ... "Test Two": "Test 2",
    ... "Test three": "Test 3",
    ... }
    >>> multiple_replace(my_dict, text)
    'Test 1, Test 1, Test 2, Test 3'

Leave a Reply

Your email address will not be published.