C# 用于验证多个电子邮件地址的正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9809357/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 10:42:08  来源:igfitidea点击:

Regex for validating multiple E-Mail-Addresses

c#regexvalidationemailrfc

提问by SeToY

I got a Regex that validates my mail-addresses like this:

我有一个正则表达式来验证我的邮件地址,如下所示:

([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)

([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)

This works perfectly fine, but only allows one e-mail to be entered. Now I wanted to extend that and allow multiple mail-addresses to be added (just like MS Outlook, for example) with a semicolon as a mail-splitter.

这工作得很好,但只允许输入一封电子邮件。现在我想扩展它并允许添加多个邮件地址(就像 MS Outlook 一样),并使用分号作为邮件拆分器。

[email protected];[email protected];[email protected]

[email protected];[email protected];[email protected]

Now I've searched and found this one:

现在我已经搜索并找到了这个:

([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}(;|$))

([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}(;|$))

This works on one point, but sadly requiresa semicolon at the end of a mail:

这在一点上有效,但遗憾的是在邮件末尾需要一个分号:

[email protected];

This is not what I want when the user only enters one e-mail.

当用户只输入一封电子邮件时,这不是我想要的。

How can I extend my regex above (the first one) to allow multiple mail-addresses to be added while let them be splitted through a semicolon?

如何扩展上面的正则表达式(第一个)以允许添加多个邮件地址,同时让它们通过分号分开?

采纳答案by JotaBe

This is your original expression, changed so that it allows several emails separated by semicolon and (optionally) spaces besides the semicolon. It also allows a single email address that doesn't end in semicolon.

这是您的原始表达式,已更改为允许多封电子邮件以分号和(可选)除分号之外的空格分隔。它还允许使用不以分号结尾的单个电子邮件地址。

This allows blank entries (no email addresses). You can replace the final * by + to require at least one address.

这允许空白条目(无电子邮件地址)。您可以将最后的 * 替换为 + 以要求至少一个地址。

(([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)(\s*;\s*|\s*$))*

If you need to allow comma, apart from semicolon, you can change this group:

如果您需要允许逗号,除了分号,您可以更改此组:

(\s*;\s*|\s*$)

by this one:

通过这个:

(\s*(;|,)\s*|\s*$)

Important note: as states in the comment by Martin, if there are additional text before or after the correct email address list, the validation will not fail. So it would work as an "email searcher". To make it work as a validator you need to add ^at the beginning of the regex, and $at the end. This will ensure that the expression matches all the text. So the full regex would be:

重要提示:正如 Martin 在评论中所述,如果在正确的电子邮件地址列表之前或之后有附加文本,则验证不会失败。所以它可以作为“电子邮件搜索器”。要使其作为验证器工作,您需要^在正则表达式的开头和$结尾添加。这将确保表达式匹配所有文本。所以完整的正则表达式将是:

^(([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)(\s*;\s*|\s*$))*$

You can add an extra \s*after the ^to tolerate blanks at the beginning of the list, like this. I.e. include ^\s*instead of simply ^The expression already tolerates blanks at the end as is.

您可以在列表开头的容忍空白\s*之后添加额外^的内容,如下所示。即包含^\s*而不是简单^的表达式已经可以容忍末尾的空白。

回答by Brian Agnew

Why not just split on the semicolon and then validate each potential email address using your existing regexp ? Writing one huge regexp is going to be very difficult and a maintenance nightmare, I suspect.

为什么不直接在分号上拆分,然后使用现有的正则表达式验证每个潜在的电子邮件地址?我怀疑编写一个巨大的正则表达式将非常困难并且是维护噩梦。

回答by PraveenVenu

Please try this

请试试这个

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

回答by Uwe Keim

In an old regex book they stated that you cannot write a regex to match allvalid email addresses (although you can come close).

在一本旧的正则表达式书中,他们说你不能写一个正则表达式来匹配所有有效的电子邮件地址(尽管你可以接近)。

Here is a websitedealing with regex and email addresses.

这是一个处理正则表达式和电子邮件地址的网站

I would recommend that you split the string at ;and ,boundaries and check each email address separately for being valid/invalid with your regex.

我建议您将字符串拆分为;,边界,并分别检查每个电子邮件地址是否与您的正则表达式有效/无效。

回答by Krumelur

Domain names are actually way more complex. For example, most TLDs are now using Unicode domain names, which are quite common in Europe. Consider the email address mailtest@пример.испытание, which is actually perfectly valid (though they can always be transcribed to the old form- [email protected]). This means that it is probably easier to define what characters are notvalid for a domain name. See ICANNs.

域名实际上要复杂得多。例如,大多数 TLD 现在使用Unicode 域名,这在欧洲非常普遍。考虑电子邮件地址mailtest@пример.испытание,它实际上是完全有效的(尽管它们总是可以转录为旧形式- [email protected])。这意味着,它可能是更容易定义哪些字符是不是有效的域名。请参阅ICANN

In addition, the TLDs are also not strictly part of the set you have defined, see IANAs list of valid TLDs. For example, [email protected] is a valid email address.

此外,TLD 也不是您定义的集合的严格组成部分,请参阅IANA 有效 TLD 列表。例如,[email protected] 是一个有效的电子邮件地址。

In short, to validate email addresses, consider going with an established third party library, unless you are dealing with a limited special case.

简而言之,要验证电子邮件地址,请考虑使用已建立的第三方库,除非您处理的是有限的特殊情况。

Now for your original question, I would recommend a preprocess stage where you split on reasonable delimiters (',' and ';'), trim whitespace (at least if dealing with user input) and validate each entry.

现在对于您的原始问题,我会推荐一个预处理阶段,您可以在其中拆分合理的分隔符(',' 和 ';'),修剪空格(至少在处理用户输入时)并验证每个条目。

回答by Shuffler

Something I've written in my days. Basic email validation is taken from practical implementation of RFC 2822

我这几天写的东西。基本的电子邮件验证取自RFC 2822 的实际实现

^([a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])(;)?)+$

matches emails with ; separator

匹配电子邮件与 ; 分隔器

I you want more separators, swap (;)? with [;,|]? within the [] brackets.

我想要更多的分隔符,交换 (;)?用 [;,|]? [] 括号内。

回答by Rob Scott

Old post - needed the same RegEx. The accepted answer did not work for me, however, this did.

旧帖子 - 需要相同的 RegEx。接受的答案对我不起作用,但是,确实如此。

^(|([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+([;.](([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+)*$

Retrieved from this post, however, the accepted answer did not work either, but the Regex on the link WITHIN the post did.

然而,从这篇文章中检索到,接受的答案也不起作用,但帖子内链接上的正则表达式起作用了。

[email protected]- validates

[email protected]- 验证

[email protected];[email protected]- validates

[email protected];[email protected]- 验证

[email protected];- does not validate

[email protected];- 不验证

empty string- validates

empty string- 验证

If you want to validate against an empty string, then remove the |at the beginning of the regex

如果要针对空字符串进行验证,请删除|正则表达式开头的

回答by Qasim Bataineh

Below is my solution and it worked as expected for me:

以下是我的解决方案,它按我的预期工作:

      var emailReg = new RegExp(/^([A-Z0-9.%+-]+@@[A-Z0-9.-]+.[A-Z]{2,6})*([,;][\s]*([A-Z0-9.%+-]+@@[A-Z0-9.-]+.[A-Z]{2,6}))*$/i);
  var emailText = $('#email').val();

  if (!emailReg.test(emailText)) {
      alert('Wrong Email Address\Addresses format! Please reEnter correct format');
        return false;
    }
}

回答by Qasim Bataineh

Here is a simple Program which does this for you without using the Regular Expression.Well Actually it does use a regular expression but we don't have to worry about it how it looks .php does this for us .

这是一个简单的程序,它在不使用正则表达式的情况下为您执行此操作。实际上,它确实使用了正则表达式,但我们不必担心它的外观。php 为我们执行此操作。

public function test_reg()

{

   $email_list = '';

        $array = explode(";",$email_list);

        foreach ($array as $value)
         {
            $value;

            if (!filter_var($value, FILTER_VALIDATE_EMAIL) === false)
             {
                 $msg =  "Email List Contains  valid email addresses.";
              } 
            else
             {
                 $msg ="Your Email list contains an invalid email at. &nbsp&nbsp &nbsp".$value;
                 break;
             }  
         }

                echo $msg;



}

You have to separate your emails by a semi colon.

您必须用分号分隔您的电子邮件。

回答by Jacob Morris

This is a very old question, but I figured I'd share my C# code.

这是一个非常古老的问题,但我想我会分享我的 C# 代码。

I decided to parse by the semicolon then check each email individually:

我决定用分号解析然后分别检查每封电子邮件:

string toAddress = "[email protected];[email protected];";
Regex rgx = new Regex(
    @"^[_a-z0-9-]+(\.[_a-z0-9-]+)*(\+[a-z0-9-]+)?@[a-z0-9-]+(\.[a-z0-9-]+)*$");

List<string> emailArray = new List<string>();

if(toAddress != null && toAddress != "")
{
    if (toAddress.IndexOf(";") != -1)
    {
        emailArray = toAddress.Replace(" ","").Split(';').ToList();
    }
    else
    {
        emailArray.Add(toAddress);
    }

    foreach (string email in emailArray)
    {
        if (rgx.IsMatch(email ?? ""))
        {
            SendEmail(email, subject, body);
        }
    }
}