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

nzrxty8p  于 2023-02-26  发布在  iOS
关注(0)|答案(8)|浏览(331)

我有一个字符串,它只需要是a-z,0-9和_
我如何检查输入是否有效?我试过这个,但它接受字母,如Å,ä,ö,øetc.

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

wz8daaqr1#

可以创建自己的角色集:

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

一旦你有了它,你就把它反转成你原来的字符串中没有的所有东西:

s = [s invertedSet];

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

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

pgccezyw2#

可以使用 predicate :

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

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

请改用nameField.text

a8jjtwal

a8jjtwal3#

更简单的方法,

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

它将字母数字和_下划线组合在一起。
你可以这样使用它

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

PS.示例从@DaveDeLong示例中复制:)

ncgqoxb0

ncgqoxb04#

使用[NSCharacterSet characterSetWithCharactersInString:]创建您自己的字符集,然后像之前那样进行修剪,看看返回的字符串是否有长度值。
或者可以使用invertedSet删除所有未设置的字符,如果这有助于生成一个干净的字符串的话。

4xy9mtcn

4xy9mtcn5#

你可以遍历字符串中的每个字符,检查它是否是字母数字:

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

tmb3ates6#

下面是在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
    }
}
qacovj5a

qacovj5a7#

正在更新Swift 5的@vikzilla答案:

extension String {

    func containsValidCharacters() -> Bool {

        var charSet = NSCharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_")
        charSet = charSet.inverted as NSCharacterSet

        let range = (self as NSString).rangeOfCharacter(from: charSet as CharacterSet as CharacterSet)

        if range.location != NSNotFound {
            return false
        }

        return true
    }
}
c9qzyr3d

c9qzyr3d8#

这是一个快速帮助器,如果它有帮助的话

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

相关问题