开发者

Check if NSString contains alphanumeric + underscore characters only

开发者 https://www.devze.com 2023-04-07 03:02 出处:网络
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.

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


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].

Use nameField.text instead.


Some more easy way,

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

It'll combine alphanumeric along with _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 :)


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

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


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
}


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

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


Updating @vikzilla answer for Swift 5:

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


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

精彩评论

暂无评论...
验证码 换一张
取 消