【问题标题】:Identify chars in alphabetical sequence OBJ-C识别字母顺序OBJ-C中的字符
【发布时间】:2012-10-29 16:54:17
【问题描述】:

我正在编写一个带有注册部分的 iOS 应用程序。我的客户有这些糟糕的验证规则,这让我抓狂。最新的规则是这样的:不要接受超过 3 个按字母顺序排列的字符,例如:“abcd”、“eFgH”、“jklM”。

但我可以按“1234”、“3456”之类的顺序接受数字...

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

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

【问题讨论】:

  • 尝试使用parse 字符串而不是使用regex

标签: objective-c ios regex validation nspredicate


【解决方案1】:

恭喜你,他们还没有注意到键盘没有字母布局:)

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 !");
}

【讨论】:

  • 我认为你应该将这一行 - currentChar &gt;= 57 &amp;&amp; currentChar &lt;= 48 - 改为这一行 - currentChar &lt;= 57 &amp;&amp; currentChar &gt;= 48,否则工作会很棒!
  • 更好的是,将 48 替换为“0”,将 57 替换为“9”。使其可读。
  • @qegal 确实需要用or 替换第二个and 并合并范围检查,谢谢。
  • 谢谢,这应该可以工作,但客户又决定实施这个。
【解决方案2】:

从可能可行的最简单的事情开始:

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;
}

【讨论】:

  • 谢谢 Rob,这应该可以解决问题,并且第一个答案的 LOC 更少。但我不再需要它了,客户不想要了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-14
  • 2018-05-03
  • 1970-01-01
  • 2020-04-16
  • 2011-08-30
相关资源
最近更新 更多