简体   繁体   English

正则表达式可以验证用分号分隔的电子邮件列表?

[英]Regex to validate a semi-colon seperated list of emails?

I have the following c# extension method for validating an email address. 我有以下用于验证电子邮件地址的c#扩展方法。 The regex came from Microsoft on their How to: Verify that Strings Are in Valid Email Format page. regex来自Microsoft,其方法如何:验证字符串是否为有效电子邮件格式页。

I need to improve this method to be able to handle a semi-colon seperated list of emails. 我需要改进此方法,以便能够处理以分号分隔的电子邮件列表。 An valid example string could be as badly formatted as: ";; ; ; xxx.sss.xxx ; ;; xxx.sss.xxx;" 有效的示例字符串的格式可能不正确,例如:“ ;;;; xxx.sss.xxx; ;; xxx.sss.xxx;”

    /// <summary>
    /// Validates the string is an Email Address...
    /// </summary>
    /// <param name="emailAddress"></param>
    /// <returns>bool</returns>
    public static bool IsValidEmailAddress(this string emailAddress)
    {
        var valid = true;
        var isnotblank = false;

        var email = emailAddress.Trim();
        if (email.Length > 0)
        {
            isnotblank = true;
            valid = Regex.IsMatch(email, @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
            @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$", RegexOptions.IgnoreCase);
        }

        return (valid && isnotblank);
    }

Microsoft's regex does a pretty good job. 微软的正则表达式做得很好。 However, it doesn't catch a few strange scenarios and a number of special characters which are valid for email. 但是,它不会遇到一些奇怪的情况以及许多对电子邮件有效的特殊字符。 I'll give you a different regex. 我给你一个不同的正则表达式。 Choose to use it or not is your prerogative. 选择是否使用它是您的特权。

I would separate the concerns by having one extension method which validates an email address and another which validates the list. 我将通过一种验证电子邮件地址的扩展方法和另一种验证列表的扩展方法来分离问题。 Do a .trim() on each email before passing it to the email validation method. 在将每个电子邮件传递给电子邮件验证方法之前,对每个电子邮件执行.trim()。 So, something like this: 因此,如下所示:

    /// <summary>
    /// Validates the string is an Email Address...
    /// </summary>
    /// <param name="emailAddress"></param>
    /// <returns>bool</returns>
    public static bool IsValidEmailAddress(this string emailAddress)
    {
        var valid = true;
        var isnotblank = false;

        var email = emailAddress.Trim();
        if (email.Length > 0)
        {
            // Email Address Cannot start with period.
            // Name portion must be at least one character
            // In the Name, valid characters are:  a-z 0-9 ! # _ % & ' " = ` { } ~ - + * ? ^ | / $
            // Cannot have period immediately before @ sign.
            // Cannot have two @ symbols
            // In the domain, valid characters are: a-z 0-9 - .
            // Domain cannot start with a period or dash
            // Domain name must be 2 characters.. not more than 256 characters
            // Domain cannot end with a period or dash.
            // Domain must contain a period
            isnotblank = true;
            valid = Regex.IsMatch(email, @"\A([\w!#%&'""=`{}~\.\-\+\*\?\^\|\/\$])+@{1}\w+([-.]\w+)*\.\w+([-.]\w+)*\z", RegexOptions.IgnoreCase) &&
                !email.StartsWith("-") &&
                !email.StartsWith(".") &&
                !email.EndsWith(".") && 
                !email.Contains("..") &&
                !email.Contains(".@") &&
                !email.Contains("@.");
        }

        return (valid && isnotblank);
    }

    /// <summary>
    /// Validates the string is an Email Address or a delimited string of email addresses...
    /// </summary>
    /// <param name="emailAddress"></param>
    /// <returns>bool</returns>
    public static bool IsValidEmailAddressDelimitedList(this string emailAddress, char delimiter = ';')
    {
        var valid = true;
        var isnotblank = false;

        string[] emails = emailAddress.Split(delimiter);

        foreach (string e in emails)
        {
            var email = e.Trim();
            if (email.Length > 0 && valid) // if valid == false, no reason to continue checking
            {
                isnotblank = true;
                if (!email.IsValidEmailAddress())
                {
                    valid = false;
                }
            }
        }
        return (valid && isnotblank);
    }

You can use the following regex to allow several emails separated by semicolon and (optionally) spaces besides the semicolon. 您可以使用以下正则表达式来允许多封电子邮件,以分号和(除分号之外)空格分隔。 It will also accept single email address that does not end in semicolon. 它还将接受不以分号结尾的单个电子邮件地址。

Right now it allows empty entries as well(no email addresses). 现在,它也允许空条目(没有电子邮件地址)。 If You wanna change it to have at least 1, then replace the final * by + to require at least one address. 如果您想将其更改为至少1,则将最后的*替换为+,以要求至少一个地址。

(([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 want to allow comma as well as semicolon, you can chage following : 如果要允许使用逗号和分号,则可以执行以下操作:

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

to this: 对此:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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