0

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?

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.