Automatically converting urls to html links
Here’s simple Python snippet for converting urls to links in single text line:
import re
link_re = re.compile('(\s+\(?|^)((http|ftp|https)://[-\w\#$%&~/.;:=,?@+]+)', re.IGNORECASE)
def autolinks(line):
return link_re.sub(r'\1<a href="\2" target="_blank">\2</a>', line)
It’s simple yet smart enough:
- doesn’t touch urls inside html links <a href=”some url”>some text</a>
- can be used with Markdown, as it doesn’t touch Markdown links
To enable auto links replacement in Markdown, you may use autolink extension.