Check NSString for special characters

后端 未结 5 2023
北恋
北恋 2020-12-23 09:39

I want to check an NSString for special characters, i.e. anything except a-z, A-Z and 0-9.

I don\'t need to check how many special characters are present, or their p

相关标签:
5条回答
  • 2020-12-23 10:18

    Here the code you can use it to check the string has any special character or not

    NSString *string = <your string>;
    
    NSString *specialCharacterString = @"!~`@#$%^&*-+();:={}[],.<>?\\/\"\'";
    NSCharacterSet *specialCharacterSet = [NSCharacterSet
                                           characterSetWithCharactersInString:specialCharacterString];
    
    if ([string.lowercaseString rangeOfCharacterFromSet:specialCharacterSet].length) {                
        NSLog(@"contains special characters");
    }
    
    0 讨论(0)
  • 2020-12-23 10:25

    This code allows only numbers in UITextField input.

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
        if ([string rangeOfCharacterFromSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]].location != NSNotFound)
            return NO;
        else
            return YES;
    
    }
    
    0 讨论(0)
  • 2020-12-23 10:30

    If you want to remove special characters & numbers from any string (even textfield text), while you are editing, these lines below are quite handy:

    #define ACCEPTABLE_CHARACTERS @"!~`@#$%^&*-+();:=_{}[],.<>?\\/|\"\'0123456789"
    
    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
        NSCharacterSet *cs = [NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARACTERS];
    
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    
        return (![string isEqualToString:filtered]) ? NO : YES;
    }
    
    0 讨论(0)
  • 2020-12-23 10:39
    NSCharacterSet * set = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
    
    if ([aString rangeOfCharacterFromSet:set].location != NSNotFound) {
      NSLog(@"This string contains illegal characters");
    }
    

    You could also use a regex (this syntax is from RegexKitLite: http://regexkit.sourceforge.net ):

    if ([aString isMatchedByRegex:@"[^a-zA-Z0-9]"]) {
      NSLog(@"This string contains illegal characters");
    }
    
    0 讨论(0)
  • 2020-12-23 10:45

    You want to search NSString using a character set if it cant find any characters in the string then rangeOfCharacterFromSet: will return a range of {NSNotFound, 0}

    The character set would be like [NSCharacterSet symbolCharacterSet] or your own set. Note you can also invert character sets so you could have a set of acceptable characters

    0 讨论(0)
提交回复
热议问题