我有一段文字如下
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 变得可点击,网址变得可点击)。但是当我点击它时,我被重定向到 localhost:5002而不是打开 Outlook。 localhost:5002是托管我的 Flask 应用程序的地方。 即使对于 url,它也不起作用。我正在使用以下代码使 url 字符串可点击。
text = text.replace('url',f'<a href "{url_link}">{url}</a>'
上面的代码使 usr 字符串可点击,但点击后它被重定向到 localhost:5002 我需要在 app.run(host=5002) 中做任何更改吗?方法?
请您参考如下方法:
您可以将 re.sub 与 lambda 一起使用:
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>'
