正则表达式匹配所有电子邮件,除了锚标签1

时间:2018-09-06 05:46:25

标签: javascript regex

我需要从带有html或不带有html的内容中查找所有电子邮件地址,并需要用链接替换。

我在正则表达式下面有一个用于查找电子邮件地址的文件,它工作正常。

(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])

以下是用于处理示例数据的演示链接: https://regexr.com/3v12e

这是锚标记正则表达式(?:(<a[^>]*>([^<]+)<\/a>))

那么如何找到除锚标记1之外的所有电子邮件地址:

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以使用类似于trash bin trick的东西。

您基本上会搜索3种情况:“ a”标签,电子邮件和“其余”。您将捕获组分配给这3种情况中的任何一种。然后,根据这些组是否为空,您可以执行不同的操作。因此,该结构为:(A_TAG)|(EMAIL)|([\s\S])(其中[\s\S]表示包括换行符在内的任何字符)

应该说顺序很重要:您希望第一组成为'a'标签,以便快速丢弃它。 “ any character”([\s\S])必须是最后一个选项,因为如果它将是第一个,则它将匹配任何内容,而其他选项则不会匹配任何文本。

const regex = /(?:(<a[^>]*>(?:[^<]+)<\/a>))|((?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\]))|([\s\S])/gm;
const str = `example@gmail.com
example@gmail.com
For more information example@gmail.com about I Can Read, 
example@gmail.com please refer to <a href="mailto:do-not@example.com">do-not@example.com</a>our website example@gmail.com
example@gmail.com
 example@gmail.com
    example@gmail.com
	 example@gmail.com
	 
	 sdfsdf example@gmail.com
example@gmail.com sdfsdfsdf`;
let m;

let acc = '';
while ((m = regex.exec(str)) !== null) {
    if (typeof(m[1])!='undefined') {
        //First group is defined: it will have a <a> tag
        //So we just add it to the acumulator as-is.
        acc += m[1];
    }
    else if (typeof(m[2])!='undefined') {
        //Second group is defined: it will have an email
        //we change it
        acc += '<a href="mailto:' + m[2] + '">' + m[2] + '</a>';
    }
    else {
        //Any other character. We just add to the accumulator
        acc += m[3];
    }
}
console.log(acc);

此外,here可以找到一个演示,只是为了直观地查看不同的捕获组。当然,对于替换,您将需要上述额外的逻辑。

相关问题