I need to remove/replace all characters except for alpha numeric, -, & from NSString. How do i construct my regular expression to achieve that I want to ensure user does not enter any characters other than alphanumeric, & and - in uitextfield. How can i do that. Previusly i Handled things in shoulchangecharactersineange, but now the filter is getting increasigly big to handle through if conditions. Regular expressions may be the best choice for my scenario. I'd apprecite your thoughts and inputs
2 Answers
-(BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)r replacementString:(NSString*)s
{
NSCharacterSet * reject = [[NSCharacterSet characterSetWithCharactersInString:@"QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890-&"] invertedSet];
if ([s rangeOfCharacterFromSet:reject].length)
{
return NO;
}
return YES;
}
Comments
You can use the NSString method rangeOfCharctersFromSet: to do this check.
First construct a character set containing your allowable characters, and then used invertedSet to get a set of all non-allowed characters. Then search your string for the range of characters in this set. If none of the characters in the set are found the return range value will be {NSNotFound, 0}
NSMutableCharacterSet *legalCharacters = [NSCharacterSet alphanumericCharacterSet];
[legalCharacters addCharactersInString:@"-&"];
NSCharacterSet *illegalCharacters = [legalCharacters invertedSet];
NSString *testString = @"ThisStringWillFail@#$%";
if ([testString rangeOfCharacterFromSet:illegalCharacters].location == NSNotFound) {
// string passed validation
} else {
// string failed validation
}
2 Comments
tc.
[NSCharacterSet alphanumericCharacterSet] returns the set of Unicode "letters" and "digits" (including all Chinese characters, for example). This is probably not what is intended.Rob
It's up to the original question's author as to how restrictive to be, but I personally hate apps that reject common accented characters for no good reason. If this is, for example, capturing proper names, it shouldn't force someone to change their name because the app lives in a 7-bit world! I personally would err towards jonkroll's character set (but use it in
shouldChangeCharactersInRange) unless there were some app requirements that precluded it.
shouldChangeCharactersInRange, but tc's answer shows how simple it can be. Whether you use his choice of 7-bit character set, or broaden it to support common European languages, like jonkroll did, is up to you. But either way, it should be pretty simple.