简体   繁体   English

如何从字符串中提取单个电子邮件地址?

[英]How to extract single email address from string?

I need to extract a single email address from this kind of string.我需要从这种字符串中提取一个电子邮件地址。

Unauthorized: Your password has expired.未经授权:您的密码已过期。 We have sent a reset password link to example@gmail.com.我们已将重置密码链接发送至 example@gmail.com。 Please check your email for details请检查您的电子邮件以获取详细信息

const string = "Unauthorized: Your password has expired. We have sent a reset password link to example@gmail.com. Please check your email for details";
const mailMatch = string.match(/(\S+@[^\s.]+\.{1}[^.]\S+)/);

The match in this case will be this `在这种情况下的比赛将是这样的`

[0: "example@gmail.com."
1: "example@gmail.com."
groups: undefined
index: 79
input: "Unauthorized: Your password has expired. We have sent a reset password link to example@gmail.com. Please check your email for details"
length: 2]

I don't want to match the dot(indicating end of the sentence) at the end of mail.我不想匹配邮件末尾的点(表示句子的结尾)。 How to change my regexp , in order to get only example@gmail.com如何更改我的正则表达式,以便仅获取example@gmail.com

You may use您可以使用

 var string = "Unauthorized: Your password has expired. We have sent a reset password link to example@gmail.com. Please check your email for details"; var mailMatch = string.match(/\\S+@[^\\s.]+\\.[^.\\s]+/); console.log(mailMatch); // => Matched text: example@gmail.com // Or, if you may have any non-whitespace chars and you want to stop at the last console.log( "The example@site.co.uk address is not available".match(/\\S+@[^\\s.]+\\.\\S+\\b/) ); // => Matched text: example@site.co.uk // Or just console.log( "The example@some.site.co.uk address is not available".match(/\\S+@\\S+\\.\\S+\\b/) ); // => Matched text: example@some.site.co.uk

Since it is not quite clear what email requirements you have a more generic example would be由于不太清楚您的电子邮件要求是什么,因此您有一个更通用的示例

s.match(/\S+@\S+\.\S+\b/)

Details细节

  • \\S+ - 1+ non-whitespace chars \\S+ - 1+ 个非空白字符
  • @ - a @ char @ - 一个@字符
  • \\S+ - 1+ non-whitespace chars \\S+ - 1+ 个非空白字符
  • \\. - a dot - 一个点
  • \\S+\\b - 1+ non-whitespace chars that end with a word boundary. \\S+\\b - 1+ 个以单词边界结尾的非空白字符。

If you need to extract valid looking emails only here is a solution with a bit amended well-known email validation regex:如果您只需要提取看起来有效的电子邮件,这里有一个解决方案,对众所周知的电子邮件验证正则表达式进行了一些修改:

 var email_rx_extract = /(?:[^<>()[\\]\\\\.,;:\\s@"]+(?:\\.[^<>()[\\]\\\\.,;:\\s@"]+)*|".+")@(?:\\[\\d{1,3}(?:\\.\\d{1,3}){3}]|(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,})(?![a-zA-Z])/g; var s = "The example@some.site.co.uk address is not available\\nBad email is example@gmail...........com."; var results = s.match(email_rx_extract); console.log(results); // => Only example@some.site.co.uk is found.

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

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