python - 在 python 中使用正则表达式将 URL 替换为链接

标签 python regex url hyperlink

如何将一些文本转换为链接?回到 PHP,我使用了这段代码,它对我的​​目的很有效:

            $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 就太好了 :)..

最佳答案

下面的代码是对 python 的简单翻译。你应该确认它确实做了你想要的。更多信息,请参阅 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

这是我这边的输出:

<a href="http://www.example.com/foo/bar.html" target="_blank">http://www.example.com</a>

关于python - 在 python 中使用正则表达式将 URL 替换为链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1112012/

相关文章:

c# - 具有最大长度的小数正则表达式

Java - 正则表达式问题

url - Chrome 浏览器不喜欢没有 http ://? 的 *.loc 域

java - 来自 URL 的 InputStream

python - 使用 Python/Elementtree 将具有相同标签的多个子元素添加到 en XML 树中

python - importlib 找不到模块

python - 在 BioPython 中使用 Entrez 从 GenBank 检索和解析蛋白质序列

regex - 将字符串中单词的首字母大写

javascript - 在 Javascript 中使用正则表达式返回 URL 参数值

python - 如何使用 Python 检测图形的转折点