转载合并自用
// 账号验证
//规则:用字母开头,使用数字与字母符号结合的方法组成6-10位的账号数
void AccountRegex()
{
string rule = "^[a-zA-Z][a-zA-Z\d!@#$%^&*.,_+-=]{6,9}$";
string account1 = "t12345@{}";
string account2 = "123456&/";
string account3 = "kt12345@{}";
Regex re = new Regex(rule);
Debug.Log(re.IsMatch(account1));//true
Debug.Log(re.IsMatch(account2));//false(解析:)
Debug.Log(re.IsMatch(account3));//false
}
表示开头元符也只用与开头,”[a-zA-Z]”表示26个字母,“\d”表示整数,“[a-zA-Z\d!@#$%^&.,_±=]”表示的意思是只要出现里面其中一个就行了,{6,9}表示按照前面的规则,内容有6-9个长度,少了不行多了也不行。
void Start()
{
RegexLevel("12345676722");//密码强度:容易
RegexLevel("mm1234elq");//密码强度:中等
RegexLevel("lqg12345...{}/3&");//密码强度:复杂
RegexLevel("1340817");//密码输入格式不正确
}
//密码验证
void RegexLevel(string input)
{
//复杂 必须有数字与字母和符号混合组成的8-15位数(就是剔除其余格式可能,留下目标格式)
string rule1 = @"^(?![a-zA-Z]{8,15}$)(?![\d{8,15}])(?![!@#$%^&*.]{8,15}$)(?![a-zA-Z\d]{8,15}$)(?![a-zA-Z!@#$%^&*.]{8,15})(?![\d!@#$%^&*.]{8,15}$)
([a-zA-Z\d!@#$%^&*.]{8,15}&)";
//中等 由数字和字母或者数字和符号或者字母和符号组成的8-15位数
string rule2 = @"^(?![a-zA-Z]{8,15}$)(?![\d{8,15}])(?![!@#$%^&*.]{8,15}$)([a-zA-Z\d]|[a-zA-Z!@#$%^&*.]|[\d!@#$%^&*.]){8,15}$";
//简单 由单一的数字或者字母或者符号组成的8-15位数
string rule3 = @"^([a-zA-Z]|[\d{8,15}]|[!@#$%^&*.]){8,15}$";
Regex r1 = new Regex(rule1);
Regex r2 = new Regex(rule2);
Regex r3 = new Regex(rule3);
if (r1.IsMatch(input))
{
Debug.Log("密码强度:复杂");
return;
}
else if (r2.IsMatch(input))
{
Debug.Log("密码强度:中等");
return;
}
else if (r3.IsMatch(input))
{
Debug.Log("密码强度:容易");
return;
}
else
Debug.Log("密码输入格式不正确");
}
“?!”标志,该标志表达的意思就是说非取内容,例如(?![a-zA-Z]{8,15}&)意思就说单独只出现字母的都不合格,还有这个(?![a-zA-Z\d]{8,15})出现字母和数字混搭的也不合格
把逻辑分开的另外一种写法
/// <summary>
/// 包含小写字母
/// </summary>
private static readonly string REG_CONTAIN_LOWERCASE_ASSERTION =
@"(?=.*[a-z])";
/// <summary>
/// 包含大写字母
/// </summary>
private static readonly string REG_CONTAIN_UPPERCASE_ASSERTION =
@"(?=.*[A-Z])";
/// <summary>
/// 包含数字
/// </summary>
private static readonly string REG_CONTAIN_DIGIT_ASSERTION =
@"(?=.*\d)";
/// <summary>
/// 包含特殊字符(https://www.owasp.org/index.php/Password_special_characters)
/// </summary>
private static readonly string REG_CONTAIN_SPECIAL_CHAR_ASSERTION =
@"(?=.*[ !""#$%&'()*+,-./:;<=>?@\[\]\^_`{|}~])";
public static readonly string PASSWORD_STRENGTH =
$"{REG_CONTAIN_LOWERCASE_ASSERTION}" +
$"{REG_CONTAIN_UPPERCASE_ASSERTION}" +
$"{REG_CONTAIN_DIGIT_ASSERTION}" +
$"{REG_CONTAIN_SPECIAL_CHAR_ASSERTION}" +
@"^.{8,32}$";
public static void TestPattern(string pattern, string input)
{
Regex regex = new Regex(pattern);
Console.WriteLine(regex.IsMatch(input));
}