iOS使用正則匹配限制輸入密碼格式


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 // (查找范圍為整個的話無效)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM