正则表达式的电子邮件匹配 [英] Regex for email matching
问题描述
我正在使用此正则表达式匹配字符串中的电子邮件地址。
I am using this regex to match email addresses in a string.
此处一切正常: http://regexr.com?31e5a
这个正则表达式:
Everything works fine here: http://regexr.com?31e5a with this regex:
([\w-\.]+)@((?:[\w]+\.)+)([a-zA-Z]{2,4})
但是当我尝试将它与javascript一起使用时,我只收到第一个电子邮件地址,而不是全部。
But when I am trying to use it with javascript, I am getting only the first email address, not all of them.
这是我的代码:
var emailsString = 'aaaaaaa@bbbb.com xxxxxxx cccccc@dddd.com';
var emails = emailsString.match(/([\w-\.]+)@((?:[\w]+\.)+)([a-zA-Z]{2,4})/)[0];
这里的广告,我只收到第一封电子邮件。
Ad here, I am getting only the first email.
如果你能帮助我,谢谢你。
If you can help me, thank you.
推荐答案
你需要添加'g'修饰符:
var emailsString = 'aaaaaaa@bbbb.com xxxxxxx cccccc@dddd.com';## Heading ##
var emails = emailsString.match(/([\w-\.]+)@((?:[\w]+\.)+)([a-zA-Z]{2,4})/g)
此外,正如本文其他地方所述,您的正则表达式与所有有效的电子邮件都不匹配。将有效电子邮件与正则表达式匹配实际上是一个非常困难的问题,但首先,TLD组件可能超过4个字符,因此您应该相应地调整它。
Also, as mentioned elsewhere in this post, your regex does not match all valid emails. Matching valid emails with regex is actually a pretty difficult problem, but to start with, the TLD component can be longer than 4 characters so you should adjust that accordingly.
我的推荐是使用此处提到的其他正则表达式与/ g修饰符组合来获取所有匹配项。
My recommendation is to use the other regex mentioned here in combination with the /g modifier to get all matches.
g修饰符用于执行全局匹配(找到所有匹配
而不是在第一次匹配后停止)。
The g modifier is used to perform a global match (find all matches rather than stopping after the first match).
这篇关于正则表达式的电子邮件匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!