按字母顺序OBJ-C识别字符

时间:2012-10-29 16:54:18

标签: objective-c ios regex validation nspredicate

我正在写一个有注册部分的iOS应用。我的客户有这些关于验证的可怕规则让我发疯。最新的规则是这样的:不要按字母顺序接受超过3个字符,例如:“abcd”,“eFgH”,“jklM”。

但我可以按顺序接受数字,如“1234”,“3456”......

要解决这些问题,我已经在使用NSPredicate和NSRegularExpression。但是我不知道正则表达式来识别这些字符,所以我在寻求你的帮助。

有人知道如何解决这个问题吗?

2 个答案:

答案 0 :(得分:2)

让我祝贺你他们还没有注意到键盘没有按字母顺序排列:)

NSString * str = [@"01234abcdsfsaasgAWEGFWAE" lowercaseString]; // make it a lower case string as you described it not case-sensitive
const char * strUTF8 = [str UTF8String]; // get char* password text for the numerical comparison

BOOL badPassword = NO;
int charIndex = 0;
int badHitCount = 0;
const int len = strlen(strUTF8);
char previousChar = strUTF8[0]; // the app is going to crash here with an empty string

// check the password
while (charIndex < len) {
    char currentChar = strUTF8[charIndex++];
    if (currentChar - previousChar == 1 && (currentChar >= 57 || currentChar <= 48)) 
    // 57 is the character '9' index at UTF8 table, letters are following this index, some characters are located before 48's '0' character though
        badHitCount++;
    else
        badHitCount = 0;
    previousChar = currentChar;

    if (badHitCount >= 3) {
        badPassword = YES;
        break;
    }
}

if (badPassword) {
    NSLog(@"You are a Bad User !");
} else {
    NSLog(@"You are a Good User !");
}

答案 1 :(得分:1)

从最简单的事情开始:

BOOL hasAlphabetSequence(NSString *s, int sequenceLength) {
    static NSString *const alphabet = @"abcdefghijklmnopqrstuvwxyz";
    s = [s lowercaseString];
    for (int i = 0, l = (int)alphabet.length - sequenceLength; i < l; ++i) {
        NSString *sequence = [alphabet substringWithRange:NSMakeRange(i, sequenceLength)];
        if ([s rangeOfString:sequence].location != NSNotFound) {
            return YES;
        }
    }
    return NO;
}