I want to allow only specific characters for a string.
Here's what I've tried.
NSString *mdn = @"010-222-1111";
NSCharacterSet *allowedCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@"+0123456789"];
NSString *trimmed = [mdn stringByTrimmingCharactersInSet:[allowedCharacterSet invertedSet]];
NSString *replaced = [mdn stringByReplacingOccurrencesOfString:@"-" withString:@""];
The result of above code is as below. The result of replaced is what I want.
trimmed : 010-222-1111
replaced : 0102221111
What am I missing here? Why doesn't invertedSet
work?
One more weird thing here. If I removed the invertedSet
part like
NSString *trimmed = [mdn stringByTrimmingCharactersInSet:allowedCharacterSet];
The result is
trimmed : -222-
I have no idea what makes this result.