Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How fill a regex string with parameters

I would like to fill regex variables with string.

import re

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

args variable is now a dict with {"action":"delete"}.

How i can reverse this process ? With args dict and regex pattern, how i can obtain the string "/robert/delete/" ?

it's possible to have a function just like this ?

def reverse(pattern, dictArgs):

Thank you

like image 868
0xBAADF00D Avatar asked Nov 07 '12 09:11

0xBAADF00D


People also ask

How do you pass a parameter in regex?

If you use a string containing the expression, you have to omit them and escape every backslash since the backslash is the escape character in strings as well. Because backslash is an escape character in strings, you need to escape all the backslashes, e.g., \\w instead of \w .

Can you use variables in regular expressions?

In a regular expression, variable values are created by parenthetical statements.


1 Answers

This function should do it

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)

You basically match the (\?P...) block and replace it with a value from the dict.

EDIT: regex is the regex string in my exmple. You can get it from patter by

regex_compiled.pattern

EDIT2: verbose regex added

like image 164
Dimitri Vorona Avatar answered Nov 15 '22 05:11

Dimitri Vorona