I'm looking for a quick and easy way to strip non-alphanumeric characters from an NSString
. Probably something using an NSCharacterSet
, but I'm tired and nothing seems to return a string containing only the alphanumeric characters in a string.
We can do this by splitting and then joining. Requires OS X 10.5+ for the componentsSeparatedByCharactersInSet:
NSCharacterSet *charactersToRemove = [[NSCharacterSet alphanumericCharacterSet] invertedSet]; NSString *strippedReplacement = [[someString componentsSeparatedByCharactersInSet:charactersToRemove] componentsJoinedByString:@""];
In Swift, the componentsJoinedByString
is replaced by join(...)
, so here it just replaces non-alphanumeric characters with a space.
let charactersToRemove = NSCharacterSet.alphanumericCharacterSet().invertedSet let strippedReplacement = " ".join(someString.componentsSeparatedByCharactersInSet(charactersToRemove))
For Swift2 ...
var enteredByUser = field.text .. or whatever let unsafeChars = NSCharacterSet.alphanumericCharacterSet().invertedSet enteredByUser = enteredByUser .componentsSeparatedByCharactersInSet(unsafeChars) .joinWithSeparator("")
If you want to delete just the one character, for example delete all returns...
enteredByUser = enteredByUser .componentsSeparatedByString("\n") .joinWithSeparator("")
What I wound up doing was creating an NSCharacterSet and the -invertedSet
method that I found (it's a wonder what an extra hour of sleep does for documentation-reading abilities). Here's the code snippet, assuming that someString
is the string from which you want to remove non-alphanumeric characters:
NSCharacterSet *charactersToRemove =
[[ NSCharacterSet alphanumericCharacterSet ] invertedSet ];
NSString *trimmedReplacement =
[ someString stringByTrimmingCharactersInSet:charactersToRemove ];
trimmedReplacement
will then contain someString
's alphanumeric characters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With