Swift -从字符串中只获取字母数字字符

1hdlvixo  于 2023-05-16  发布在  Swift
关注(0)|答案(4)|浏览(146)

我正在尝试为String类创建一个内部函数,以便只获取AlphaNumeric字符并返回一个字符串。我遇到了一些关于如何使用Regex将匹配转换回字符串的错误。有人能告诉我如何修复代码或是否有更简单的方法吗?
我想要这样的东西

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()
    }
}
xxhby3vn

xxhby3vn1#

您可以直接使用replacingOccurrences(从输入字符串中删除所有不重叠的匹配项)和[^A-Za-z0-9]+模式:

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]+模式是一个 * 否定字符类 *,它匹配除类中定义的字符之外的任何字符,一次或多次出现(由于+量词)。
参见regex demo

rjjhvcjd

rjjhvcjd2#

试试下面的扩展:

extension String {
    var alphanumeric: String {
        return self.components(separatedBy: CharacterSet.alphanumerics.inverted).joined().lowercased()
    }
}

用法:print("alphanumeric :", "_<$abc$>_".alphanumeric)
输出:abc

k2arahey

k2arahey3#

你也可以使用characterset来实现

extension String {
    var alphaNumeric: String {
       components(separatedBy: CharacterSet.alphanumerics.inverted).joined()
    }
}
2ic8powd

2ic8powd4#

components(separatedBy: CharacterSet.alphanumerics.inverted).joined()这样的东西不应该对日语这样的特殊字符起作用
下面应该可以工作。测试

extension String {    
    var toAlphaNumeric: String {
        let pattern = "[^A-Za-z0-9]+"
        
        return self.replacingOccurrences(of: pattern, with: "", options: [.regularExpression])
    }
}

print("Ad asd asdaあsだsd123".toAlphaNumeric)

Result: Adasdasdassd123

您可以将[^A-Za-z0-9]+更改为[^A-Za-z]+[^0-9]+

相关问题