C#正则表达式校验某个字符串是否是合格的email
可以借助正则表达式校验某个字符串是否是合规的电子邮箱。对于邮箱的正则表达式有严格的模式,如:^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$
对应的C#实现如下:
using System;
using System.Text.RegularExpressions;
namespace EmailRegexValidateExample
{
/// <summary>
/// 如何确认字符串是有效的电子邮件格式
/// https://learn.microsoft.com/zh-cn/dotnet/standard/base-types/how-to-verify-that-strings-are-in-valid-email-format
/// </summary>
internal class Program
{
public static string EMAIL_PATTERN = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
/// <summary>
/// 验证字符串email是否为有效的邮箱地址
/// </summary>
/// <param name="email"></param>
/// <returns></returns>
public static bool IsEmail(string email)
{
Regex regEmail = new Regex(EMAIL_PATTERN);
Match match = regEmail.Match(email);
return match.Success;
}
static void Main(string[] args)
{
string email1 = "alice@example.com";
if (IsEmail(email1))
{
Console.WriteLine("email1 " + email1 + " is valid email address");
} else {
Console.WriteLine("email1 " + email1 + " is invalid email address");
}
string email2 = "alice..bob@example.com";
if (IsEmail(email1))
{
Console.WriteLine("email2 " + email2 + " is valid email address");
} else {
Console.WriteLine("email2 " + email1 + " is invalid email address");
}
}
}
}
执行结果如下图所示: