Question about parsing a string

Fredrik Lundh fredrik at pythonware.com
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=http://www.whatever.org][/url]' I would like
> to generate this string:
> '<a href="http://www.whatever.org">http://www.whatever.org</a>'
>
> If the string is e.g. '[url=http://www.whatever.org]My link[/url]' I
> would like to generate this string:
> '<a href="http://www.whatever.org">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)

usage:

>>> fixurl("[url=http://www.whatever.org][/url]")
"<a href='http://www.whatever.org'>http://www.whatever.org</a>"
>>> fixurl("[url=http://www.whatever.org]My link[/url]")
"<a href='http://www.whatever.org'>My link</a>"

</F>






More information about the Python-list mailing list