Regular expression for 5 comma separated email id

拟墨画扇 提交于 2019-12-24 12:15:05

问题


I trying to validate 5 comma separated email id in one regular expression. I currntly using below regex

^([\w+-.%]+@[\w-.]+\.[A-Za-z]{2,4},?)+$

This is valid for one email id.

I would like to know how I can achieve the same, any small inputs on the same is also greatly appreciated.

Thanks in advance.


回答1:


First of all, fix the pattern: - in between two chars inside a character class forms a range. So, the email part of your regex should be [-\w+.%]+@[\w-.]+\.[A-Za-z]{2,4} (note the position of - in the first character class, in the second, it is OK to put it between a shorthand character class \w and the next char).

Next, to match 1 to 5 comma-separated emails, you need to match the first one, and then match 0 to 4 emails. And add anchors around the pattern to make sure the pattern matches the whole string:

^[-\w+.%]+@[\w-.]+\.[A-Za-z]{2,4}(?:,[-\w+.%]+@[\w-.]+\.[A-Za-z]{2,4}){0,4}$

Basically, ^<EMAIL>(?:,<EMAIL>){0,4}$:

  • ^ - start of string
  • <EMAIL> - an email pattern of yours
  • (?: - start of a non-capturing group acting as a container for a sequence of patterns:
    • , - a comma
    • <EMAIL> - an email pattern of yours
  • ){0,4} - zero to four occurrences of these sequences above
  • $ - end of string.

Another idea is to split with , and then validate:

var s = "abc@gg.com,abc2@gg.com,abc3@gg.com,abc4@gg.com,abc5@gg.com";
var re = /^[-\w+.%]+@[\w-.]+\.[A-Za-z]{2,4}$/;
var items = s.split(",");
if (items.length <= 5 && items.filter(function(x) { return re.test(x); }).length === items.length ) {
   console.log("VALID => ", items);
} else {
   console.log("INVALID!");
}



回答2:


Below regex for javaScript you can use for multiple comma separated email id, hope this work for you

/^(\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]{2,4}\s*?,?\s*?)+$/


来源:https://stackoverflow.com/questions/44175731/regular-expression-for-5-comma-separated-email-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!