malisit malisit - 1 month ago 19
Python Question

Regex in Django template tag matches only once

I have a template tag like this:

@register.filter(name='bknz')
def bknz(text):
pattern = re.compile(r"(?P<start>.*)\(bkz: (?P<bkz>.*)\)(?P<end>.*)")
link = r'\g<start>(bkz: <a href="/baslik/\g<bkz>" title="%\g<bkz> search Twitter">\g<bkz></a>)\g<end>'
text = pattern.sub(link,text)
return mark_safe(text)


It changes the (bkz: something) to linked (bkz: something). It works fine but only once. When I put a few (bkz: sth) to my object. It only renders the last one in object as changed version. How can I run this as much as necessary? Thanks.

Answer

This one worked.

@register.filter(name='bknz')
def bknz(text):
    pattern = re.compile(r"(?P<start>.*?)\(bkz: (?P<bkz>[^)]*)\)(?P<end>.*?)")
    link = r'\g<start>(bkz: <a href="/baslik/\g<bkz>"  title="\g<bkz>">\g<bkz></a>)\g<end>'
    text = pattern.sub(link, text)
    return mark_safe(text)
Comments