nama depan
nama depan

Reputation: 19

Convert python regex backreference to lower

I created function for replace string with dictionary,

def tolower(text):
    patterns = {
        "\[(.*?)\]": (r"[\1-123]").lower()
    }
    for key in patterns:
        text = re.sub(key, patterns[key], text)
    return text
print tolower("[IMG]UPPER[/IMG]")

But I want python backreference \1 convert the string to lower after replace.

So, I'm expecting the result like this :

[img-123]UPPER[/img-123]

Can someone please tell me how it's working with replacing regex backreference?

Upvotes: 0

Views: 245

Answers (2)

sidney
sidney

Reputation: 827

You can pass a function to re.sub() that will allow you to do this, here is an example:

 def replaceLower(match):
     return '[' + match.group(1).lower() + '-123]'

To use it, instead of having each key map to a regular expression, map the key to a function that is called by re.sub:

def tolower(text):
    patterns = {
        "\[(.*?)\]": replaceLower
    }
    for key in patterns:
        text = re.sub(key, patterns[key], text)
    return text

Upvotes: 2

Jon Clements
Jon Clements

Reputation: 142166

Change to using a callable as the replacement argument:

import re

def tolower(text):
    patterns = {
        "\[(.*?)\]": lambda m: '[{}-123]'.format(m.group(1).lower())
    }
    for key in patterns:
        text = re.sub(key, patterns[key], text)
    return text
print(tolower("[IMG]UPPER[/IMG]"))
# [img-123]UPPER[/img-123]

Upvotes: 1

Related Questions