从 NSString 中去除非字母数字字符
我正在寻找一种快速简便的方法来从 NSString
中删除非字母数字字符。可能是使用 NSCharacterSet 的东西,但我累了,似乎没有任何东西返回只包含字符串中字母数字字符的字符串。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
我们可以通过拆分然后合并来做到这一点。组件SeparatedByCharactersInSet 需要 OS X 10.5+:
We can do this by splitting and then joining. Requires OS X 10.5+ for the componentsSeparatedByCharactersInSet:
在 Swift 中,
componentsJoinedByString
被join(...)
替换,因此这里它只是用空格替换非字母数字字符。对于 Swift2 ...
如果您只想删除一个字符,例如删除所有返回...
In Swift, the
componentsJoinedByString
is replaced byjoin(...)
, so here it just replaces non-alphanumeric characters with a space.For Swift2 ...
If you want to delete just the one character, for example delete all returns...
我最后做的是创建一个 NSCharacterSet 和我发现的
-invertedSet
方法(令人惊奇的是,额外的一个小时的睡眠对于文档阅读能力有何影响)。下面是代码片段,假设someString
是要从中删除非字母数字字符的字符串:trimmedReplacement
将包含someString
的字母数字字符。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 thatsomeString
is the string from which you want to remove non-alphanumeric characters:trimmedReplacement
will then containsomeString
's alphanumeric characters.已接受答案的 Swift 3 版本:
Swift 3 version of accepted answer:
Swift 5,扩展:
Swift 5, Extension:
清理类别
我有一个方法调用
stringByStrippingCharactersInSet:
和stringByCollapsingWhitespace
,可以方便地直接插入。A Cleanup Category
I have a method call
stringByStrippingCharactersInSet:
andstringByCollapsingWhitespace
that might be convenient to just drop-in.以下是 Cameron 类别 的 Swift 版本作为扩展:
Here’s a Swift version of Cameron’s category as an extension:
我认为简单的循环执行时间会更快:
The plain cycle would be the faster execution time I think:
更有效的方法
这是比提供的答案或作为类别
This is a more effective way than the provided answer
or as a Category