Tim
Tim

Reputation: 169

Passing values into regex match function

In python (it's a Django filter), I'm doing this:

lReturn = re.sub(r'\[usecase:([ \w]+)]', r'EXTEND WITH <a href="/usecase/%s/\1/">\1</a>' % pCurrentProjectName, lReturn)

I'd like to use a function instead of a string (so I can check that the usercase is a valid name), so it would change to this:

def _match_function(matchobj):
    lMatch = matchobj.group(1)
    return "EXTEND WITH <a href='/usecase/%s/%s/'>%s</a>" % (pCurrentProjectName, lMatch, lMatch)

lReturn = re.sub(r'\[usecase:([ \w]+)]', _match_function, lReturn)

How do I get pCurrentProjectName into the _match_function() function?

Upvotes: 2

Views: 173

Answers (1)

Felix Kling
Felix Kling

Reputation: 816334

You could create a function that returns a function (a closure):

def _match_function(name):
    def f(matchobj):
        lMatch = matchobj.group(1)
        return "EXTEND WITH <a href='/usecase/%s/%s/'>%s</a>" % (name, lMatch, lMatch)
    return f

lReturn = re.sub(r'\[usecase:([ \w]+)]', _match_function(pCurrentProjectName), lReturn)

Upvotes: 4

Related Questions