【发布时间】: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