Python regex将文本中的url替换为链接(从PHP转换)

2024-10-01 17:25:49 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能把这个PHP正则表达式转换成Python吗?我试了几次都没有成功:

function convertLinks($text) {
    return preg_replace("/(?:(http:\/\/)|(www\.))(\S+\b\/?)([[:punct:]]*)(\s|$)/i",
    "<a href=\"http://$2$3\" rel=\"nofollow\">$1$2$3</a>$4$5", $text);
}

编辑: 我发现[:punct:]可以替换为[!”#$%&;'()*+,-./:;<;=>;?@[\]^{{}~],所以我试了一下:

^{pr2}$

但我收到了convertLinks(u)测试的“unmatched group”错误www.example.com网站试验”)。在


Tags: texthttp编辑returnwwwfunctionreplacerel
2条回答

如果您想在python中使用regex,应该考虑使用^{}模块。在这个例子中,特别是^{}。在

语法类似于:

output = re.sub(regular_expression, what_it_should_be_replaced_by, input)

别忘了re.sub()返回被替换的字符串。在

表达式使用了一些在Python中工作方式不同的特性。在

  • Python没有[[:punct:]]字符组;我使用了一个POSIX regex reference来扩展它。

  • 表达式使用可选组;在开头匹配http://www.,但随后在替换中同时使用。在Python中这将失败。解决方案:使用替换函数。

因此,要获得相同的功能,您可以使用:

import re

_link = re.compile(r'(?:(http://)|(www\.))(\S+\b/?)([!"#$%&\'()*+,\-./:;<=>?@[\\\]^_`{|}~]*)(\s|$)', re.I)

def convertLinks(text): 
    def replace(match):
        groups = match.groups()
        protocol = groups[0] or ''  # may be None
        www_lead = groups[1] or ''  # may be None
        return '<a href="http://{1}{2}" rel="nofollow">{0}{1}{2}</a>{3}{4}'.format(
            protocol, www_lead, *groups[2:])
    return _link.sub(replace, text)

演示:

^{pr2}$

相关问题 更多 >

    热门问题