【问题标题】:Replace email id by HTML Tag to make a hyperlink inside the text用 HTML 标记替换电子邮件 ID 以在文本内创建超链接
【发布时间】:2019-06-14 11:26:54
【问题描述】:

我有一段文字如下

For further details, please contact abc.helpdesk@xyz.com

我想用<a href "abc.helpdesk@xyz.com">abc.helpdesk@xyz.com</a>替换上面文字中提到的电子邮件ID,这样当上面的文字出现在网页上时,电子邮件ID就会成为一个可点击的对象

到目前为止,我已经尝试了以下

text = 'For further details, please contact abc.helpdesk@xyz.com'
email_pat = re.findall(r'[\w\.-]+@[\w\.-]+\.\w+',text)
email_str = ' '.join(email_pat) #converts the list to string
text_rep = ext.replace(email_str,'<a href "email_str">email_str</a>')

上面的代码替换了电子邮件字符串,但实际上不是创建超链接,而是执行以下操作

For further details, please contact <a href "email_str">email_str</a>

有没有办法解决这个问题?

编辑 当我在 Flask 中使用上述解决方案时,在前端我得到了想要的结果(即电子邮件 ID 变得可点击,url 变得可点击)。但是当我点击它时,我被重定向到localhost:5002,而不是打开 Outlook。 localhost:5002 是托管我的 Flask 应用程序的地方。 即使对于网址也不起作用。我正在使用以下代码使 url 字符串可点击。

text = text.replace('url',f'<a href "{url_link}">{url}</a>'

上面的代码使 usr 字符串可以点击,但是点击后它被重定向到localhost:5002 我需要对app.run(host=5002) 方法进行任何更改吗?

【问题讨论】:

  • 您可能希望使用 "mailto:" 将前缀属性设为 href 属性,以便点击自动打开电子邮件客户端 - &lt;a href "mailto:abc.helpdesk@xyz.com"&gt;abc.helpdesk@xyz.com&lt;/a&gt;
  • @snakechamberb 我确实做到了这一点,并且运行良好。不管怎么说,还是要谢谢你。但是,你能帮我处理 URL 部分吗?我还在挣扎。

标签: python regex


【解决方案1】:

您可以将re.sublambda 一起使用:

import re
s = 'For further details, please contact abc.helpdesk@xyz.com'
new_s = re.sub('[\w\.]+@[\w\.]+', lambda x:f'<a href="{x.group()}">{x.group()}</a>', s)

输出:

'For further details, please contact <a href="abc.helpdesk@xyz.com">abc.helpdesk@xyz.com</a>'

【讨论】:

    【解决方案2】:

    你的实际问题是这条线:

    text_rep = ext.replace(email_str, '<a href "email_str">email_str</a>')
    

    这正是你所说的,但你想要的是:

    text_rep = ext.replace(email_str, f'<a href "{email_str}">{email_str}</a>')
    

    不是用包含email_str 的文字字符串替换邮件地址,而是格式化字符串,使其包含邮件地址。这是假设您运行 Python 3,对于 Python 2,它更像是:

    text_rep = ext.replace(email_str, '<a href "{email_str}">{email_str}</a>'.format(email_str=email_str))
    

    但是,请注意,您匹配邮件地址的正则表达式做了一些假设,可以在此处找到更好的版本Are email addresses allowed to contain non-alphanumeric characters?

    此外,您的代码假定源文本字符串中只有一个邮件地址,因为您要加入结果。更好的解决方案可能是将每个单独的邮件地址替换为正确的替换地址。

    import re
    
    input_text = 'For further details, contact admin@mywebsite.org or the webmaster webmaster123@hotmail.com'
    
    output_text = re.sub(
        r'(?sm)(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@(([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{2,})',
        r'<a href="\g<0>">\g<0></a>', input_text)
    
    print(output_text)
    

    请注意,这只需要一个基本的re.sub

    【讨论】:

    • 太好了@Grismar。您能否建议如何使用相同的技术获取多个“网址”?我有一个很长的正则表达式。
    • 获取任何 URL 的正则表达式都会很长,遗憾的是 - URL 很长、复杂且多变,因此没有捷径可走。这个问题有一个很好的解决方案,可以输入 5497 个字符。那时,您必须想知道正则表达式是否是最佳解决方案,或者您是否应该让用户在编写时将 URL 标记为链接。 stackoverflow.com/questions/161738/… - 不过方法是一样的。
    猜你喜欢
    • 2019-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-25
    • 2014-04-15
    • 2010-10-12
    • 1970-01-01
    • 2013-06-17
    相关资源
    最近更新 更多