我用这个
@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"
Regexp来验证电子邮件
([\w\.\-]+) -用于第一级域名(许多字母和数字,也有点和连字符) ([\w\-]+) -用于二级域 ((\.(\w){2,3})+) -这是用于其他级别域(从3到无穷),其中包括一个点和2或3个字面量
这个正则表达式有什么问题?
编辑:它与“something@someth.ing”电子邮件不匹配
我用这个
@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"
Regexp来验证电子邮件
([\w\.\-]+) -用于第一级域名(许多字母和数字,也有点和连字符) ([\w\-]+) -用于二级域 ((\.(\w){2,3})+) -这是用于其他级别域(从3到无穷),其中包括一个点和2或3个字面量
这个正则表达式有什么问题?
编辑:它与“something@someth.ing”电子邮件不匹配
当前回答
string patternEmail = @"(?<email>\w+@\w+\.[a-z]{0,3})";
Regex regexEmail = new Regex(patternEmail);
其他回答
string patternEmail = @"(?<email>\w+@\w+\.[a-z]{0,3})";
Regex regexEmail = new Regex(patternEmail);
这是目前为止我最喜欢的方法:
public static class CommonExtensions
{
public static bool IsValidEmail(this string thisEmail)
=> !string.IsNullOrWhiteSpace(thisEmail) &&
new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$").IsMatch(thisEmail);
}
然后使用创建的字符串扩展名,如:
if (!emailAsString.IsValidEmail()) throw new Exception("Invalid Email");
以下是我从这里收集信息和微软文档后的解决方案:
/// <summary>
/// * TLD support from 2 to 5 chars (modify the values as you want)
/// * Supports: abc@gmail.com.us
/// * Non-sensitive case
/// * Stops operation if takes longer than 250ms and throw a detailed exception
/// </summary>
/// <param name="email"></param>
/// <returns>valid: true | invalid: false </returns>
/// <exception cref="ArgumentException"></exception>
private bool validateEmailPattern(string email) {
try {
return Regex.IsMatch(email,
@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,5})+)$",
RegexOptions.None, TimeSpan.FromMilliseconds(250));
} catch (RegexMatchTimeoutException) {
// throw an exception explaining the task was failed
_ = email ?? throw new ArgumentException("email, Timeout/failed regexr processing.", nameof(email));
}
}
public static bool ValidateEmail(string str)
{
return Regex.IsMatch(str, @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
}
我使用上面的代码来验证电子邮件地址。
如果它不起作用,请告诉我:)
public static bool isValidEmail(this string email)
{
string[] mail = email.Split(new string[] { "@" }, StringSplitOptions.None);
if (mail.Length != 2)
return false;
//check part before ...@
if (mail[0].Length < 1)
return false;
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^[a-zA-Z0-9_\-\.]+$");
if (!regex.IsMatch(mail[0]))
return false;
//check part after @...
string[] domain = mail[1].Split(new string[] { "." }, StringSplitOptions.None);
if (domain.Length < 2)
return false;
regex = new System.Text.RegularExpressions.Regex(@"^[a-zA-Z0-9_\-]+$");
foreach (string d in domain)
{
if (!regex.IsMatch(d))
return false;
}
//get TLD
if (domain[domain.Length - 1].Length < 2)
return false;
return true;
}