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

前端 未结 13 1210
一整个雨季
一整个雨季 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:45
    ^([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+,*[\W]*)+$
    

    This will also work. It's a little bit stricter on emails, and doesn't that there be more than one email address entered or that a comma be present at all.

    0 讨论(0)
  • 2020-12-15 07:45

    The easiest solution would be as following. This will match the string with comma-separated list. Use the following regex in your code.

    Regex: '[^,]+,?'

    0 讨论(0)
  • 2020-12-15 07:56

    Try this:

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

    Adding the + after the parentheses means that the preceding group can be present 1 or more times.

    Adding the ^ and $ means that anything between the start of the string and the start of the match (or the end of the match and the end of the string) causes the validation to fail.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-15 07:58
    ^([\w+-.%]+@[\w-.]+\.[A-Za-z]+)(, ?[\w+-.%]+@[\w-.]+\.[A-Za-z]+)*$
    

    Works correctly with 0 or 1 spaces after each comma and also for long domain extensions

    0 讨论(0)
  • 2020-12-15 07:59
    ^([\w+.%-]+@[\w.-]+\.[A-Za-z]{2,})( *,+ *(?1))*( *,* *)$
    

    The point about requiring a comma between groups, but not necessarily at the end is handled here - I'm mostly adding this as it includes a nice subgroup with the (?1) so you only define the actual email address regex once, and then can muck about with delimiters.

    Email address ref here: https://www.regular-expressions.info/email.html

    0 讨论(0)
提交回复
热议问题