代码之家  ›  专栏  ›  技术社区  ›  AjmeraInfo

正则表达式匹配除锚标记1以外的所有电子邮件

  •  2
  • AjmeraInfo  · 技术社区  · 8 年前

    我需要找到所有的电子邮件地址从内容与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

    这里是锚标记regex (?:(<a[^>]*>([^<]+)<\/a>))

    enter image description here

    1 回复  |  直到 8 年前
        1
  •  1
  •   AjmeraInfo    8 年前

    你可以用类似于 trash bin trick

    您基本上搜索3个案例:一个“a”标签、一封电子邮件和“其他”。你可以给这三个案例中的任何一个分配一个捕获组。然后根据这些组是否为空,您可以执行不同的操作。所以,这个结构: (A_TAG)|(EMAIL)|([\s\S]) (其中 [\s\S]

    应该说,顺序很重要:您希望第一个组成为“a”标记,以便快速丢弃它。“任何角色”( [\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 您可以找到一个演示,只是为了直观地看到不同的捕获组。当然,对于替换,您需要上面描述的额外逻辑。