malisit malisit - 1 year ago 125
Python Question

Regex in Django template tag matches only once

I have a template tag like this:

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 Source

This one worked.

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download