简体   繁体   中英

Regex for matching multiple emails

Right now I have the regex \\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)* to match an email address, for this situation that is good.

I have tried various things for csv cell matching but I can't seem to get them to work for this.

What I need is something that matches the regex above, but have a delimiter between, there are three different delimiters '|' ',' ';' '|' ',' ';' , for example I want to match

example@example.com

example@example.com|example@example.com|example@example.com

example@example.com,example@example.com,example@example.com

example@example.com;example@example.com;example@example.com

I also don't care about whitespace, so it needs to account for them adding extra spaces in, while still accounting for above, for example:

example@example.com | example@example.com|example@example.com

It also needs to be able to use a combination of delimiters

example@example.com,example@example.com;example@example.com|example@example.com

I am doing this in c#

Note, I have looked at this How to match a comma separated list of emails with regex?

But I am not sure how to modify ^([\\w+-.%]+@[\\w-.]+\\.[A-Za-z]{2,4},?)+$ to meet my needs

Currently I have

(\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*[\s?[,|\||;|]\s?]?)+$

I'd use a combination of String.Split() and the MailAddress constructor. Something like this:

public bool ValidAddressText(string input)
{
    string[] addresses = input.Split(new Char[] { ',', ';', '|' });
    foreach (string address in addresses)
    {
        address = address.Trim();
        try
        {
            if (address == "")
            {
                return false;
            }

            new MailAddress(address);
        }
        catch(FormatException)
        {
            return false;
        }
    }

    return true;
}

This will catch all the edge cases that the regular expression won't and even get better over time as the .NET Framework is updated. It also simplifies the handling of the delimiters and whitespace.

Try Something like this (;|\\||,)

I recommend the Tool RegExBuddy, you can try your Pattern so Easy with this and it's always a good help for me, to get the right pattern! There is a trial Version!

I came up with this:

(\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*(\s?[,|\||;|]\s?)?)+$

I believe it resolves my problem, any suggestions?

I'd use lookbehind and lookahead for this:

(?<=\s|\||;|,|^)[\w.+-]+@(?:[\w-]+\.){1,2}(?:[a-z]{2,6})(?:\.[a-z]{2,6})?(?=\s|\||;|,|$)

You can test this regex here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM