Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
    }
}
like image 850
user3628240 Avatar asked Aug 28 '18 07:08

user3628240


People also ask

How do I check if a string is alphanumeric Swift?

In Swift, how can I check if a String is alphanumeric, ie, if it contains only one or more alphanumeric characters [a-zA-Z0-9] , excluding letters with diacritics, eg, é.

Does alphanumeric include special characters?

An alphanumeric password contains numbers, letters, and special characters (like an ampersand or hashtag). In theory, alphanumeric passwords are harder to crack than those containing just letters.

What is Alnum in regex?

The Alphanumericals are a combination of alphabetical [a-zA-Z] and numerical [0-9] characters, 62 characters.

How do I remove a specific character from a string in Swift?

Removing the specific character To remove the specific character from a string, we can use the built-in remove() method in Swift. The remove() method takes the character position as an argument and removed it from the string.


3 Answers

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.

like image 84
Wiktor Stribiżew Avatar answered Oct 20 '22 19:10

Wiktor Stribiżew


Try below extension:

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

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

Output : abc

like image 35
Moayad Al kouz Avatar answered Oct 20 '22 19:10

Moayad Al kouz


You can also use characterset for this like

extension String {
    var alphaNumeric: String {
       components(separatedBy: CharacterSet.alphanumerics.inverted).joined()
    }
}
like image 32
Thahir Avatar answered Oct 20 '22 19:10

Thahir