1. 程式人生 > >C# 校驗 正則

C# 校驗 正則

regex bool ring false ret case a-z ase stat

郵箱驗證

/// <summary>
/// 是否郵箱
/// </summary>
/// <param name="value">郵箱地址</param>
/// <param name="isRestrict">是否按嚴格模式驗證</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 name="value">值</param>
/// <param name="isRestrict">是否按嚴格模式驗證</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);
}

C# 校驗 正則