2010-06-08 5 views
2

En python (il est un filtre Django), je fais ceci:valeurs Passing en fonction match regex

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

Je voudrais utiliser une fonction au lieu d'une chaîne (je peux vérifier que la usercase est un nom valide), il changerait à ceci:

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) 

Comment puis-je obtenir pCurrentProjectName dans la fonction _match_function()?

Répondre

4

Vous pouvez créer une fonction qui retourne une fonction (un 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

Excellent, merci. – Tim