匹配电子邮件地址不包含在HTML标记中

问题描述:

我需要突出显示文本中的电子邮件地址,但如果包含在HTML标记,内容或属性中,则不会突出显示它们。匹配电子邮件地址不包含在HTML标记中

例如,串[email protected]必须不能被处理的字符串中<a href="mailto:[email protected]">[email protected]</a>转换为<a href="mailto:[email protected]">[email protected]</a>

但是电子邮件地址。

我已经试过这样的正则表达式:

(?<![":])[a-zA-Z0-9._%-+][email protected][a-zA-Z0-9._%-]+.[a-zA-Z]{2,6}(?!")

,但它不能正常工作。

+0

重复:http://stackoverflow.com/questions/401726/regex-that-only-matches-text-thats-not-part-of-html-markup-python – msw 2010-04-29 02:30:12

我会猜测你的源文本是一个HTML文件,它只包含了一些包含的电子邮件地址的锚定标记。如果这是真的,那么您将无法使用正则表达式来可靠匹配未标记的电子邮件地址。例如,给定输入:

... 
<P>You'll find a lot more written by <A 
href="mailto:[email protected]" 
title="some text including [email protected]"> 

[email protected] 
</A>. 
</P> 
... 

就不可能词汇的href与地址相关联,也排除[email protected]。您需要使用HTML解析器; BeautifulSoup很受欢迎。