Question about parsing a string

Fredrik Lundh fredrik at
Mon Oct 10 10:20:23 CEST 2005

Nico Grubert wrote:

> I would like to parse a string in Python.
> If the string is e.g. '[url=][/url]' I would like
> to generate this string:
> '<a href=""></a>'
> If the string is e.g. '[url=]My link[/url]' I
> would like to generate this string:
> '<a href="">My link</a>'
> Any idea how I can do this? Maybe with regular expressions?

here's one way to do it:

import re, cgi

def fixurl(text):
    def fixup(m):
        link, text = m.groups()
        text = text.strip() or link
        return "<a href='%s'>%s</a>" % (cgi.escape(link), cgi.escape(text))
    return re.sub(r"\[url=([^]]+)\]([^[]*)\[/url\]", fixup, text)


>>> fixurl("[url=][/url]")
"<a href=''></a>"
>>> fixurl("[url=]My link[/url]")
"<a href=''>My link</a>"


More information about the Python-list mailing list