从JS中的字符串中提取名称和电子邮件
问题描述:
如何从字符串中提取名称和电子邮件,电子邮件用逗号分隔。
How can I extract the name and email from a string, where emails are separated by commas.
以下正则表达式对于个人电子邮件而言非常棒,但不是
The regex below works great for individual emails, but not for emails within a string.
(?:"?([^"]*)"?\s)?(?:<?(.+@[^>]+)>?)
strong>注意名称中的逗号。
Note the comma within the name as well.
johndoe@baidu.com, John <johndoe@google.com>, John D, A <johndoe@bing.com>, "John Doe , Yen" <johndoe@163.com>
输出:
Name: null
Email: johndoe@baidu.com
Name: John
Email: johndoe@google.com
Name: John D, A
Email: johndoe@bing.com
Name: John Doe , Yen
Email: johndoe@163.com
答
很难判断数据是否变化或保持不变,但这是我的尝试:
It's hard to tell if the data will change or remain the same, but here's my attempt:
var re = /(?:"?([A-Z][^<"]+)"?\s*)?<?([^>\s,]+)/g;
while (m = re.exec(str)) {
if(m[1]) { m[1] = m[1].trim() }
console.log("Name: " + m[1]);
console.log("Email: " + m[2]);
}