How to match a comma separated list of emails with regex?

前端 未结 13 1208
一整个雨季
一整个雨季 2020-12-15 07:29

Trying to validate a comma-separated email list in the textbox with asp:RegularExpressionValidator, see below:



        
13条回答
  •  囚心锁ツ
    2020-12-15 07:57

    I'm a bit late to the party, I know, but I figured I'd add my two cents, since the accepted answer has the problem of matching email addresses next to each other without a comma.

    My proposed regex is this:

    ^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}(,[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,})*$

    It's similar to the accepted answer, but solves the problem I was talking about. The solution I came up with was instead of searching for "an email address followed by an optional comma" one or more times, which is what the accepted answer does, this regex searches for "an email address followed by an optional comma prefixed email address any number of times".

    That solves the problem by grouping the comma with the email address after it, and making the entire group optional, instead of just the comma.

    Notes: This regex is meant to be used with the insensitive flag enabled.
    You can use whichever regex to match an email address you please, I just used the one that I was already using. You would just replace each [A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,} with whichever regex you want to use.

提交回复
热议问题