Check NSString for special characters

后端 未结 5 2025
北恋
北恋 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: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;
    }
    

提交回复
热议问题