Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strip Non-Alphanumeric Characters from an NSString

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.

like image 584
Jeff Kelley Avatar asked Nov 01 '09 04:11

Jeff Kelley


3 Answers

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:@""]; 
like image 146
user102008 Avatar answered Sep 20 '22 21:09

user102008


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("") 
like image 30
Amr Hossam Avatar answered Sep 20 '22 21:09

Amr Hossam


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.

like image 28
Jeff Kelley Avatar answered Sep 22 '22 21:09

Jeff Kelley