从NSString中去除非字母数字字符

我正在寻找一种快速简单的方法来从NSString去除非字母数字字符。 可能是使用NSCharacterSet东西,但我累了,似乎没有任何东西返回一个string中只包含字母数字字符。

我们可以通过分裂然后join来做到这一点。 对于componentsSeparatedByCharactersInSet需要OS X 10.5+:

 NSCharacterSet *charactersToRemove = [[NSCharacterSet alphanumericCharacterSet] invertedSet]; NSString *strippedReplacement = [[someString componentsSeparatedByCharactersInSet:charactersToRemove] componentsJoinedByString:@""]; 

在Swift中, componentsJoinedByStringjoin(...)取代,所以在这里它只是用一个空格replace非字母数字字符。

 let charactersToRemove = NSCharacterSet.alphanumericCharacterSet().invertedSet let strippedReplacement = " ".join(someString.componentsSeparatedByCharactersInSet(charactersToRemove)) 

对于Swift2 …

 var enteredByUser = field.text .. or whatever let unsafeChars = NSCharacterSet.alphanumericCharacterSet().invertedSet enteredByUser = enteredByUser .componentsSeparatedByCharactersInSet(unsafeChars) .joinWithSeparator("") 

如果你想删除只有一个字符,例如删除所有返回…

  enteredByUser = enteredByUser .componentsSeparatedByString("\n") .joinWithSeparator("") 

我最终做的是创build一个NSCharacterSet和我发现的-invertedSet方法(这是一个奇迹是什么一个额外的小时睡眠文件阅读能力)。 这里是代码片段,假设someString是你想要删除非字母数字字符的string:

 NSCharacterSet *charactersToRemove = [[ NSCharacterSet alphanumericCharacterSet ] invertedSet ]; NSString *trimmedReplacement = [ someString stringByTrimmingCharactersInSet:charactersToRemove ]; 

然后trimmedReplacement将包含someString的字母数字字符。

Swift 3版本接受的答案:

 let unsafeChars = CharacterSet.alphanumerics.inverted let myStrippedString = myString.components(separatedBy: unsafeChars).joined(separator: "") 

清理类别

我有一个方法调用stringByStrippingCharactersInSet:stringByCollapsingWhitespace可能方便只是插入。

 @implementation NSString (Cleanup) - (NSString *)clp_stringByStrippingCharactersInSet:(NSCharacterSet *)set { return [[self componentsSeparatedByCharactersInSet:set] componentsJoinedByString:@""]; } - (NSString *)clp_stringByCollapsingWhitespace { NSArray *components = [self componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; components = [components filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self <> ''"]]; return [components componentsJoinedByString:@" "]; } @end 

下面是Cameron类别的一个Swift版本作为扩展:

 extension String { func stringByStrippingCharactersInSet(set:NSCharacterSet) -> String { return (self.componentsSeparatedByCharactersInSet(set) as NSArray).componentsJoinedByString("") } func stringByCollapsingWhitespace() -> String { var components:NSArray = self.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) let predicate = NSPredicate(format: "self <> ''", argumentArray: nil) components = components.filteredArrayUsingPredicate(predicate) return components.componentsJoinedByString(" ") } } 

简单的循环将是我认为更快的执行时间:

 @implementation NSString(MyUtil) - (NSString*) stripNonNumbers { NSMutableString* res = [NSMutableString new]; //NSCharacterSet *numericSet = [NSCharacterSet decimalDigitCharacterSet]; for ( int i=0; i < self.length; ++i ) { unichar c = [self characterAtIndex:i]; if ( c >= '0' && c <= '9' ) // this looks cleaner, but a bit slower: [numericSet characterIsMember:c]) [res appendFormat:@"%c", c]; } return res; } @end 

这是比提供的答案更有效的方法

 + (NSString *)alphanumericString:(NSString *)s { NSCharacterSet * charactersToRemove = [[NSCharacterSet alphanumericCharacterSet] invertedSet]; NSMutableString * ms = [NSMutableString stringWithCapacity:[s length]]; for (NSInteger i = 0; i < s.length; ++i) { unichar c = [s characterAtIndex:i]; if (![charactersToRemove characterIsMember:c]) { [ms appendFormat:@"%c", c]; } } return ms; } 

或作为一个类别

 @implementation NSString (Alphanumeric) - (NSString *)alphanumericString { NSCharacterSet * charactersToRemove = [[NSCharacterSet alphanumericCharacterSet] invertedSet]; NSMutableString * ms = [NSMutableString stringWithCapacity:[self length]]; for (NSInteger i = 0; i < self.length; ++i) { unichar c = [self characterAtIndex:i]; if (![charactersToRemove characterIsMember:c]) { [ms appendFormat:@"%c", c]; } } return ms; } @end