iOS判斷字符串是否符合格式要求

1. 判斷是否爲中國大陸手機號碼

- (BOOL)isWellFormedChineseMobileNumber {
    BOOL isWellFormed;
    if (self.length == 11) {
        // China Mobile: 134~139, 147, 150~152, 157~159, 178, 182~184, 187~188, 1705
        NSString *ChinaMobile = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        // China Unicom: 130~132, 145, 155~156, 176, 185~186, 1709
        NSString *ChinaUnicom = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        // China Telecom: 133, 153, 177, 180~181, 189, 1700
        NSString *ChinaTelecom = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}|(1700)\\d{7}$";

        NSPredicate *ChinaMobileInspect = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", ChinaMobile];
        NSPredicate *ChinaUnicomInspect = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", ChinaUnicom];
        NSPredicate *ChinaTelecomInspect = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", ChinaTelecom];

        if (([ChinaMobileInspect evaluateWithObject:self] == YES) || ([ChinaUnicomInspect evaluateWithObject:self] == YES) || ([ChinaTelecomInspect evaluateWithObject:self] == YES)) {
            isWellFormed = YES;
        } else {
            isWellFormed = NO;
        }

    } else {
        isWellFormed = NO;
    }
    return isWellFormed;
}

2. 判斷是否爲郵箱地址

- (BOOL)isWellFormedEmailAddress {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailAddressInspect = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailAddressInspect evaluateWithObject:self];
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章