转换python正则表达式反向引用

2024-07-08 07:47:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了用字典替换字符串的函数

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]")

但我希望python backreference\1在替换后将字符串转换为lower。在

所以,我期待这样的结果:

^{pr2}$

有人能告诉我用替换regex backreference是怎么工作的吗?在


Tags: key函数字符串textinreimgfor
2条回答

您可以向^{}传递一个允许您执行此操作的函数,下面是一个示例:

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

要使用它,请将键映射到re.sub调用的函数,而不是将每个键映射到正则表达式:

^{pr2}$

更改为使用callable作为替换参数:

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]

相关问题 更多 >

    热门问题