验证字符串是否是有效的电子邮件地址的最优雅的代码是什么?


当前回答

基于@Cogwheel的回答,我想分享一个修改后的解决方案,适用于SSIS和“脚本组件”:

Place the "Script Component" into your Data Flow connect and then open it. In the section "Input Columns" set the field that contains the E-Mail Adresses to "ReadWrite" (in the example 'fieldName'). Switch back to the section "Script" and click on "Edit Script". Then you need to wait after the code opens. Place this code in the right method: public override void Input0_ProcessInputRow(Input0Buffer Row) { string email = Row.fieldName; try { System.Net.Mail.MailAddress addr = new System.Net.Mail.MailAddress(email); Row.fieldName= addr.Address.ToString(); } catch { Row.fieldName = "WRONGADDRESS"; } }

然后,您可以使用条件分割过滤掉所有无效记录或任何您想做的事情。

其他回答

我从第1条中得到Phil的答案,并创建了这个类。 这样调用它:bool isValid = Validator.EmailIsValid(emailString);

下面是这个类:

using System.Text.RegularExpressions;

public static class Validator
{

    static Regex ValidEmailRegex = CreateValidEmailRegex();

    /// <summary>
    /// Taken from http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx
    /// </summary>
    /// <returns></returns>
    private static Regex CreateValidEmailRegex()
    {
        string validEmailPattern = @"^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|"
            + @"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)"
            + @"@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$";

        return new Regex(validEmailPattern, RegexOptions.IgnoreCase);
    }

    internal static bool EmailIsValid(string emailAddress)
    {
        bool isValid = ValidEmailRegex.IsMatch(emailAddress);

        return isValid;
    }
}
For the simple email like goerge@xxx.com, below code is sufficient. 

 public static bool ValidateEmail(string email)
        {
            System.Text.RegularExpressions.Regex emailRegex = new System.Text.RegularExpressions.Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
            System.Text.RegularExpressions.Match emailMatch = emailRegex.Match(email);
            return emailMatch.Success;
        }
public static bool IsEmail(string strEmail)
{
    Regex rgxEmail = new Regex(@"^([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})(\]?)$");
    return rgxEmail.IsMatch(strEmail);
}
   public bool IsValidEmail(string email)
    {
        try
        {
            var addr = new System.Net.Mail.MailAddress(email);
            return addr.Address == email;
        }
        catch
        {
            return false;
        }
    }

老实说,在产品代码中,我所做的最好的事情就是检查@符号。

我从来没有在一个地方完全验证电子邮件。你知道我怎么判断它是否有效吗?如果发送出去了。如果没有,那就糟了,如果有,生活就好了。这就是我需要知道的。