从JS中的字符串中提取名称和电子邮件 [英] Extract name and email from string in JS
本文介绍了从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]);
}
这篇关于从JS中的字符串中提取名称和电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文