繁体   English   中英

如何创建用于在字符串中查找电子邮件地址的 JavaScript 正则表达式?

[英]How can I create a JavaScript regex for finding email addresses in strings?

我有一个逻辑应用程序,它由收件箱中的电子邮件触发。 一切正常,除了一些电子邮件在我不想要的时候通过。 或者更确切地说,带有 image001.png@01D766B1.7C184990 图像描述的电子邮件签名正在通过。 我认为这可能是我的正则表达式允许它,但我对正则表达式不太擅长。

这是我到目前为止的代码:

 var reg = /([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\\.[a-zA-Z0-9_-]+)/gi; var emailData = " \\n\\n'Phonenumber2@test.com'\\n\\n \\n\\n DevOps\\n[cid:image001.png@01D766B1.7C184990]\\n\\n "; //Matching email signatures var matches = emailData .match(reg); console.log(matches);

我需要正则表达式来返回任何电子邮件地址的列表,但它们需要完全形成。 与上面提到的那个缺少 .com(或 .org 等)不同。

您的正则表达式(允许带有@.

 const regex = /([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\\.[a-zA-Z0-9_-]+)/gm; const str = `Phonenumber2@test.com Phonenumber2@test.info image001.png@01D766B1.7C184990 Phonenumber2@test.org`; let m; while ((m = regex.exec(str)) !== null) { // This is necessary to avoid infinite loops with zero-width matches if (m.index === regex.lastIndex) { regex.lastIndex++; } console.log(m[0]); }

#1 last 之后不允许有数字.

 const regex = /([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\\.[a-zA-Z_-]+)/gm; const str = `Phonenumber2@test.com Phonenumber2@test.info image001.png@01D766B1.7C184990 Phonenumber2@test.org`; let m; while ((m = regex.exec(str)) !== null) { // This is necessary to avoid infinite loops with zero-width matches if (m.index === regex.lastIndex) { regex.lastIndex++; } console.log(m[0]); }

#2 限制 last 之后的字符. 最少 2 个和最多 7 个字符{2,7}$

 const regex = /([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\\.[a-zA-Z0-9_-]{2,7}$)/gm; const str = `Phonenumber2@test.com Phonenumber2@test.info image001.png@01D766B1.7C184990 Phonenumber2@test.org`; let m; while ((m = regex.exec(str)) !== null) { // This is necessary to avoid infinite loops with zero-width matches if (m.index === regex.lastIndex) { regex.lastIndex++; } console.log(m[0]); }

#3 定义一个可能的顶级域名列表,(com|org|info)

 const regex = /([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\\.(com|org|info)$)/gm; const str = `Phonenumber2@test.com Phonenumber2@test.info image001.png@01D766B1.7C184990 Phonenumber2@test.org`; let m; while ((m = regex.exec(str)) !== null) { // This is necessary to avoid infinite loops with zero-width matches if (m.index === regex.lastIndex) { regex.lastIndex++; } console.log(m[0]) }

看看 - https://ihateregex.io/expr/email/

不想打破它,但通过正则表达式进行电子邮件匹配即使不是不可能也很难。

一种方法是将事物与域名TDN结尾进行匹配(您可以创建一组所有 tdn 并匹配或仅限制正则表达式的结尾部分 -修改后的正则表达式并从那里过滤掉它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM