【问题标题】:Email Id validation not accepting underscore before @ symbol [duplicate]电子邮件 ID 验证不接受 @ 符号前的下划线 [重复]
【发布时间】:2013-02-11 16:30:13
【问题描述】:

我有以下用于电子邮件 ID 验证的代码。我正在使用正则表达式来做到这一点。 但是,以下电子邮件 ID 无效。

test_@gmail.com

应该在正则表达式中进行哪些更改,以便它通过电子邮件 ID (test_@gmail.com)

 public static bool IsValidEmail(string strIn)
        {
            invalid = false;
            if (String.IsNullOrEmpty(strIn))
                return false;

            // Use IdnMapping class to convert Unicode domain names. 
            try
            {

                strIn = Regex.Replace(strIn, @"(@)(.+)$", DomainMapper);

            }
            catch (Exception e)
            {
                Utility.writeToLogFile(String.Format("Error while validating the Email Address {0}. Error Code.e", strIn.ToString(), e));
                return false;
            }

            if (invalid)
                return false;

            // Return true if strIn is in valid e-mail format. 
            try
            {
                return Regex.IsMatch(strIn,
                      @"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
                      @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$",
                      RegexOptions.IgnoreCase);


            }
            catch (Exception e)
            {
                Utility.writeToLogFile(String.Format("Error while validating the Email Address {0}. Error Code.e", strIn.ToString(), e));
                return false;
            }
        }

【问题讨论】:

  • 请看下面的问题,它是由@Alex 提供的已被接受的答案(最简单的方法,如果他们已经做过,让微软来做):stackoverflow.com/questions/5342375/…(顺便说一句,请确保您要问的问题不存在)
  • 另外(这只是一个建议):您应该尝试尊重 C# 所采用的“Pascal-Case 约定”,其中指出方法名称应始终大写:Utility.writeToLogFile 应该是Utility.WriteToLogFile。你当然明白,如果你不遵守约定,你的代码没有任何问题。如果你这样做,那只是一件好事。
  • +1 表示尊重“Pascal-Case 约定”。

标签: c# regex email-validation


【解决方案1】:

你的正则表达式失败了

test_@gmail.com

因为(?&lt;=[0-9a-z])@ 部分明确要求“@”前有一个字母或数字。

对于解决方案,我还建议 this answer,就像 Eduard Dumitru 在他的评论中一样。

【讨论】:

    猜你喜欢
    • 2010-10-19
    • 1970-01-01
    • 1970-01-01
    • 2018-07-10
    • 1970-01-01
    • 2017-02-05
    • 2011-07-16
    • 2016-06-24
    • 1970-01-01
    相关资源
    最近更新 更多