使用python中的regex将URL替换为链接 [英] Replace URL with a link using regex in python

查看:128
本文介绍了使用python中的regex将URL替换为链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将某些文字转换为链接?回到PHP,我使用了一段适用于我的目的的代码:

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);

我在Python中试过,但是无法让它工作..如果非常好的话有人可以把它翻译成Python:)..

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

推荐答案

下面的代码是对python的简单翻译。你应该确认它实际上做了你想要的。有关详细信息,请参阅 Python Regular Expression HOWTO

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>

这篇关于使用python中的regex将URL替换为链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆