gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 20:33:12 31 4
gpt4 key购买 nike

我需要从这种字符串中提取一个电子邮件地址。

Unauthorized: Your password has expired. We have sent a reset password link to 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+)/);

在这种情况下匹配将是这个 `

[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]

我不想匹配邮件末尾的点(表示句子的结尾)。如何更改我的正则表达式,以便仅获取 example@gmail.com

最佳答案

你可以使用

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

由于不太清楚电子邮件要求是什么,您有一个更通用的示例

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

详情

  • \S+ - 1+ 个非空白字符
  • @ - @ 字符
  • \S+ - 1+ 个非空白字符
  • \. - 一个点
  • \S+\b - 1+ 个以单词边界结尾的非空白字符。

如果您只需要提取看起来有效的电子邮件,这里有一个解决方案,其中对众所周知的电子邮件验证正则表达式进行了一些修改:

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.

关于javascript - 如何从字符串中提取单个电子邮件地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57609671/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com