C# 校验 正则

时间:2022-05-09 09:35:52

/// <summary>
/// 是否邮箱
/// </summary>
/// <param>邮箱地址</param>
/// <param>是否按严格模式验证</param>
/// <returns></returns>
public static bool IsEmail(string value, bool isRestrict=false)
{
    if (value.IsEmpty())
    {
        return false;
    }
    string pattern = isRestrict
        ? @"^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&‘\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$"
        : @"^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$";
       
    return value.IsMatch(pattern, RegexOptions.IgnoreCase);
}

/// <summary>
/// 是否存在邮箱
/// </summary>
/// <param>值</param>
/// <param>是否按严格模式验证</param>
/// <returns></returns>
public static bool HasEmail(string value, bool isRestrict = false)
{
    if (value.IsEmpty())
    {
        return false;
    }
    string pattern = isRestrict
        ? @"^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&‘\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$"
        : @"^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$";
    return value.IsMatch(pattern, RegexOptions.IgnoreCase);
}