Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace URL with a link using regex in python

how do I convert some text to a link? Back in PHP, I used this piece of code that worked well for my purpose:

            $text = preg_replace("#(^|[\n ])(([\w]+?://[\w\#$%&~.\-;:=,?@\[\]+]*)(/[\w\#$%&~/.\-;:=,?@\[\]+]*)?)#is", "\\1<a href=\"\\2\" target=\"_blank\">\\3</a>", $text);
            $text = preg_replace("#(^|[\n ])(((www|ftp)\.[\w\#$%&~.\-;:=,?@\[\]+]*)(/[\w\#$%&~/.\-;:=,?@\[\]+]*)?)#is", "\\1<a href=\"http://\\2\" target=\"_blank\">\\3</a>", $text);

I tried around in Python, but was unable to get it to work.. Would be very nice if someone could translate this to Python :)..

like image 736
user122750 Avatar asked Sep 05 '25 11:09

user122750


1 Answers

The code below is a simple translation to python. You should confirm that it actually does what you want. For more information, please see the Python Regular Expression HOWTO.

import re

pat1 = re.compile(r"(^|[\n ])(([\w]+?://[\w\#$%&~.\-;:=,?@\[\]+]*)(/[\w\#$%&~/.\-;:=,?@\[\]+]*)?)", re.IGNORECASE | re.DOTALL)

pat2 = re.compile(r"#(^|[\n ])(((www|ftp)\.[\w\#$%&~.\-;:=,?@\[\]+]*)(/[\w\#$%&~/.\-;:=,?@\[\]+]*)?)", re.IGNORECASE | re.DOTALL)


urlstr = 'http://www.example.com/foo/bar.html'

urlstr = pat1.sub(r'\1<a href="\2" target="_blank">\3</a>', urlstr)
urlstr = pat2.sub(r'\1<a href="http:/\2" target="_blank">\3</a>', urlstr)

print urlstr

Here's what the output looks like at my end:

<a href="http://www.example.com/foo/bar.html" target="_blank">http://www.example.com</a>
like image 52
ars Avatar answered Sep 08 '25 05:09

ars