Check if NSString contains alphanumeric + underscore characters only

后端 未结 7 1822
余生分开走
余生分开走 2021-01-30 00:52

I\'ve got a string that needs to be only a-z, 0-9 and _

How do I check if the input is valid? I\'ve tried this but it accepts letter like å,ä,ö,ø etc.

NS         


        
7条回答
  •  轮回少年
    2021-01-30 01:21

    You could loop through the every character in the string and check that it's alphanumeric:

    BOOL isMatch = YES;
    for (int i = 0; i < [string length]; i++) {
        unichar c = [string characterAtIndex:i];
        if (!isalnum(c) && c != '_') {
            isMatch = NO;
            break;
        }
    }
    if (isMatch) {
        // valid
    } else {
        // invalid
    }
    

提交回复
热议问题