Find & Replace hyperlinks in a string

MonkeeSage MonkeeSage at
Tue Nov 27 10:55:22 CET 2007

On Nov 27, 1:37 am, Nico Grubert <nicogrub... at> wrote:
> Hi there,
> I have a string containing some hyperlinks. I'd like to replace every
> hyperlink with a HTML style link.
> Example:
> --------
> Replace
>    ''
> with
>    '<a href=""></a>'
> What's the best way to do this if I have a few hundret strings to check?
> Thanks in advance,
> Nico

Well, this isn't the most robust and someone will probably say not to
use regular expressions, but the Q&D way is:

import re
fixed = re.sub(r'(http:[^\s\n\r]+)', r'<a href="\1">\1</a>',

NB. If the URLs are malformed (like have spaces in them, or are broken
over several lines) this won't work right.


More information about the Python-list mailing list