如何使用参数填充正则表达式字符串

0xB*_*00D 8 python regex string django

我想用字符串填充正则表达式变量.

import re

hReg = re.compile("/robert/(?P<action>([a-zA-Z0-9]*))/$")
hMatch = hReg.match("/robert/delete/")
args = hMatch.groupdict()
Run Code Online (Sandbox Code Playgroud)

args变量现在是一个带有{"action":"delete"}的词典.

我该如何扭转这一过程?使用args dict和regex模式,我如何获得字符串"/ robert/delete /"?

它有可能像这样有一个功能吗?

def reverse(pattern, dictArgs):
Run Code Online (Sandbox Code Playgroud)

谢谢

Dim*_*ona 3

这个功能应该可以做到

def reverse(regex, dict):
    replacer_regex = re.compile('''
        \(\?P\<         # Match the opening
            (.+?)       # Match the group name into group 1
        \>\(.*?\)\)     # Match the rest
        '''
        , re.VERBOSE)

    return replacer_regex.sub(lambda m : dict[m.group(1)], regex)
Run Code Online (Sandbox Code Playgroud)

您基本上匹配 (\?P...) 块并将其替换为字典中的值。

编辑: regex 是我的示例中的正则表达式字符串。你可以从 patter 中得到它

regex_compiled.pattern
Run Code Online (Sandbox Code Playgroud)

EDIT2:添加了详细的正则表达式