检查NSString是否仅包含字母数字和下划线字符 [英] Check if NSString contains alphanumeric + underscore characters only

查看:139
本文介绍了检查NSString是否仅包含字母数字和下划线字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,只需要是a-z,0-9和_

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.

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

推荐答案

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

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

这篇关于检查NSString是否仅包含字母数字和下划线字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆