views:

811

answers:

2

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.

+1  A: 

This will help you out but read it when you're not tired!!

Stripping out a set of characters from an NSString

ennuikiller
Thanks! I wound up just using NSCharacterSet, but this article led me down the right path.
Jeff Kelley
cool, glad to have helped!
ennuikiller
+5  A: 

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.

Jeff Kelley
FYI, stringByTrimmingCharactersInSet: only removes characters from the beginning and end of the string. Maybe that's what you wanted.
Ken Aspeslagh
Hmm, good point, Ken. I didn't know that. It still works for my needs, but that's good to know.
Jeff Kelley