1. 程式人生 > >iOS判斷字串中包含數字和字母的幾種情況

iOS判斷字串中包含數字和字母的幾種情況

//直接呼叫這個方法就行

-(int)checkIsHaveNumAndLetter:(NSString*)password{

//數字條件

NSRegularExpression *tNumRegularExpression = [NSRegularExpressionregularExpressionWithPattern:@"[0-9]"options:NSRegularExpressionCaseInsensitiveerror:nil];

//符合數字條件的有幾個位元組

    NSUInteger tNumMatchCount = [tNumRegularExpression numberOfMatchesInString

:password

                                                                       options:NSMatchingReportProgress

                                                                         range:NSMakeRange(0, password.length)];

//英文字條件

NSRegularExpression *tLetterRegularExpression = [NSRegularExpression

regularExpressionWithPattern:@"[A-Za-z]"options:NSRegularExpressionCaseInsensitiveerror:nil];

//符合英文字條件的有幾個位元組

    NSUInteger tLetterMatchCount = [tLetterRegularExpression numberOfMatchesInString:password options:NSMatchingReportProgress range:NSMakeRange(0, password.length)];

    if (tNumMatchCount == password.length

) {

//全部符合數字,表示沒有英文

        return 1;

    } else if (tLetterMatchCount == password.length) {

//全部符合英文,表示沒有數字

        return 2;

    } else if (tNumMatchCount + tLetterMatchCount == password.length) {

//符合英文和符合數字條件的相加等於密碼長度

        return 3;

    } else {

        return 4;

//可能包含標點符號的情況,或是包含非英文的文字,這裡再依照需求詳細判斷想呈現的錯誤

    }

}