Swift - 从字符串中只获取字母数字字符 [英] Swift - Getting only AlphaNumeric Characters from String
问题描述
我正在尝试为 String
类创建一个内部函数,以仅获取 AlphaNumeric 字符并返回一个字符串.我遇到了一些关于如何使用正则表达式将匹配项转换回字符串的错误.有人可以告诉我如何修复代码或者是否有更简单的方法?
I'm trying to create an internal function for the String
class to get only AlphaNumeric characters and return a string. I'm running into a few errors with how to convert the matches back into a string using Regex. Can someone tell me how to fix the code or if there's an easier way?
我想要这样的东西
let testString = "_<$abc$>_"
let alphaNumericString = testString.alphaNumeric() //abc
到目前为止我有:
extension String {
internal func alphaNumeric() -> String {
let regex = try? NSRegularExpression(pattern: "[^a-z0-9]", options: .caseInsensitive)
let string = self as NSString
let results = regex?.matches(in: self, options: [], range: NSRange(location: 0, length: string.length))
let matches = results.map {
String(self[Range($0.range, in: self)!])
}
return matches.join()
}
}
推荐答案
您可以直接使用 replacingOccurrences
(从输入字符串中删除所有非重叠匹配项)和 [^A-Za-z0-9]+
模式:
You may directly use replacingOccurrences
(that removes all non-overlapping matches from the input string) with [^A-Za-z0-9]+
pattern:
let str = "_<$abc$>_"
let pattern = "[^A-Za-z0-9]+"
let result = str.replacingOccurrences(of: pattern, with: "", options: [.regularExpression])
print(result) // => abc
[^A-Za-z0-9]+
模式是一个否定字符类,它匹配除类中定义的字符以外的任何字符,一个或多个出现次数(由于 +
量词).
The [^A-Za-z0-9]+
pattern is a negated character class that matches any char but the ones defined in the class, one or more occurrences (due to +
quantifier).
查看正则表达式演示.
这篇关于Swift - 从字符串中只获取字母数字字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!