'Swift - Getting only AlphaNumeric Characters from String

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?

I want something like this

let testString = "_<$abc$>_"
let alphaNumericString = testString.alphaNumeric() //abc

So far I have:

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


Solution 1:[1]

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

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).

See the regex demo.

Solution 2:[2]

Try below extension:

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

Usage: print("alphanumeric :", "_<$abc$>_".alphanumeric)

Output : abc

Solution 3:[3]

You can also use characterset for this like

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Wiktor Stribiżew
Solution 2 Moayad Al kouz
Solution 3