ios 检查 NSString 是否仅包含字母数字 + 下划线字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7546235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 21:38:01  来源:igfitidea点击:

Check if NSString contains alphanumeric + underscore characters only

iosobjective-c

提问by David

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

我有一个字符串,只需要 az、0-9 和 _

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

如何检查输入是否有效?我试过这个,但它接受像 ?,?,?,? 等等。

NSString *string = [NSString stringWithString:nameField.text];
NSCharacterSet *alphaSet = [NSCharacterSet alphanumericCharacterSet];
[string stringByTrimmingCharactersInSet:alphaSet];
[string stringByReplacingOccurrencesOfString:@"_" withString:@""];
BOOL valid = [[string stringByTrimmingCharactersInSet:alphaSet] isEqualToString:@""];

回答by Dave DeLong

You can create your own character set:

您可以创建自己的字符集:

NSCharacterSet *s = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_"];

Once you have that, you invert it to everything that's not in your original string:

一旦你有了它,你就可以将它反转为不在原始字符串中的所有内容:

s = [s invertedSet];

And you can then use a string method to find if your string contains anything in the inverted set:

然后您可以使用字符串方法来查找您的字符串是否包含倒排集中的任何内容:

NSRange r = [string rangeOfCharacterFromSet:s];
if (r.location != NSNotFound) {
  NSLog(@"the string contains illegal characters");
}

回答by Sinetris

You can use a predicate:

您可以使用谓词:

NSString *myRegex = @"[A-Z0-9a-z_]*"; 
NSPredicate *myTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", myRegex]; 
NSString *string = nameField.text;
BOOL valid = [myTest evaluateWithObject:string];

Edit:I don't noticed that you are using [NSString stringWithString:nameField.text].

编辑:我没有注意到您正在使用[NSString stringWithString:nameField.text].

Use nameField.textinstead.

使用nameField.text来代替。

回答by Hemang

Some more easy way,

一些更简单的方法,

NSMutableCharacterSet *allowedSet = [NSMutableCharacterSet characterSetWithCharactersInString:@"_"];
[allowedSet formUnionWithCharacterSet:[NSCharacterSet alphanumericCharacterSet]];
NSCharacterSet *forbiddenSet = [allowedSet invertedSet];

It'll combine alphanumeric along with _underscore.

它将结合字母数字和 _underscore。

you can use it like,

你可以像这样使用它

NSRange r = [string rangeOfCharacterFromSet:forbiddenSet];
if (r.location != NSNotFound) {
  NSLog(@"the string contains illegal characters");
}

PS. example copied from @DaveDeLong example :)

附注。从@DaveDeLong 示例复制的示例:)

回答by Paul Lynch

Create your own character set using [NSCharacterSet characterSetWithCharactersInString:], then trim as you were doing to see if the returned string has a length value.

使用 创建您自己的字符集[NSCharacterSet characterSetWithCharactersInString:],然后像您一样修剪以查看返回的字符串是否具有长度值。

Or you could use invertedSetto remove all non-set characters, if that would help to produce a cleaned string.

或者您可以使用invertedSet删除所有未设置的字符,如果这有助于生成一个干净的字符串。

回答by Alex Nichol

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
}

回答by vikzilla

Here's how you can do it in Swift (as an extension of the String class):

以下是在 Swift 中的方法(作为 String 类的扩展):

extension String {

     func containsValidCharacters() -> Bool {

        var charSet = NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_")
        charSet = charSet.invertedSet

        let range = (self as NSString).rangeOfCharacterFromSet(charSet)

        if range.location != NSNotFound {
            return false
        }

        return true
    }
}

回答by ifrapps

this is a quick helper if it helps

如果有帮助,这是一个快速的帮手

-(BOOL)isString:(NSString *)s{
    char letter = 'A';
    //BOOL isLetter=NO;
    for (int i=0; i<26; i++) {
        NSString *temp = [NSString stringWithFormat:@"%c",letter+i];
        if ([s isEqualToString:temp]) {
            return YES;
        }
    }
    return NO;
}