在python(它是一个Django过滤器)中,我这样做:
lReturn = re.sub(r'\[usecase:([ \w]+)]', r'EXTEND WITH <a href="/usecase/%s/\1/">\1</a>' % pCurrentProjectName, lReturn)
我想使用函数而不是字符串(所以我可以检查用户名是否是有效名称),所以它会改为:
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)
如何将pCurrentProjectName引入_match_function()函数?
答案 0 :(得分:4)
您可以创建一个返回函数的函数(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)