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()
}
}
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, é.
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.
The Alphanumericals are a combination of alphabetical [a-zA-Z] and numerical [0-9] characters, 62 characters.
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.
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.
Try below extension:
extension String {
var alphanumeric: String {
return self.components(separatedBy: CharacterSet.alphanumerics.inverted).joined().lowercased()
}
}
Usage: print("alphanumeric :", "_<$abc$>_".alphanumeric)
Output : abc
You can also use characterset for this like
extension String {
var alphaNumeric: String {
components(separatedBy: CharacterSet.alphanumerics.inverted).joined()
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With