1、代碼實作"密碼至少為9位,并需包含大寫字母、小寫字母、數字或特殊字元等三種"
傳回0、1、2為格式不正确,傳回4為密碼格式正确
-(int)checkIsHaveNumAndLetter:(NSString*)password
{
//數字條件
NSRegularExpression *tNumRegularExpression = [NSRegularExpression regularExpressionWithPattern:@"[0-9]" options:NSRegularExpressionCaseInsensitive error:nil];
//符合數字條件的有幾個位元組
NSUInteger tNumMatchCount = [tNumRegularExpression numberOfMatchesInString:password
options:NSMatchingReportProgress
range:NSMakeRange(0, password.length)];
//英文字條件
NSRegularExpression *sLetterRegularExpression = [NSRegularExpression regularExpressionWithPattern:@"[a-z]" options:NSRegularExpressionDotMatchesLineSeparators error:nil];
//符合英文字條件的有幾個位元組
NSUInteger sLetterMatchCount = [sLetterRegularExpression numberOfMatchesInString:password options:NSMatchingReportProgress range:NSMakeRange(0, password.length)];
//英文字條件
NSRegularExpression *tLetterRegularExpression = [NSRegularExpression regularExpressionWithPattern:@"[A-Z]" options:NSRegularExpressionDotMatchesLineSeparators error:nil];
//符合英文字條件的有幾個位元組
NSUInteger tLetterMatchCount = [tLetterRegularExpression numberOfMatchesInString:password options:NSMatchingReportProgress range:NSMakeRange(0, password.length)];
if (password.length < 9) {
// 密碼長度不正确
return 0;
} else {
// 沒有大寫或小寫
if (tLetterMatchCount == 0 || sLetterMatchCount == 0) {
return 1;
} else {
if (tNumMatchCount > 0) {
return 4;
} else{
if(tNumMatchCount + tLetterMatchCount + sLetterMatchCount < password.length){
return 4;
} else{
return 2;
}
}
}
}
}
需注意:NSRegularExpressionOptions,如果不區分大小寫可以使用 NSRegularExpressionCaseInsensitive
NSRegularExpressionCaseInsensitive = 1 << 0, // 不區分大小寫的
NSRegularExpressionAllowCommentsAndWhitespace = 1 << 1, // 忽略空格和# -
NSRegularExpressionIgnoreMetacharacters = 1 << 2, // 整體化
NSRegularExpressionDotMatchesLineSeparators = 1 << 3, // 比對任何字元,包括行分隔符
NSRegularExpressionAnchorsMatchLines = 1 << 4, // 允許^和$在比對的開始和結束行 NSRegularExpressionUseUnixLineSeparators = 1 << 5, // (查找範圍為整個的話無效) NSRegularExpressionUseUnicodeWordBoundaries = 1 << 6 // (查找範圍為整個的話無效)
轉載于:https://www.cnblogs.com/yang-shuai/p/5920015.html