开发者

Passing values into regex match function

In python (it开发者_如何学C'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?


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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜