How to remove special characters from string in Swift
1 min readMay 7, 2021
I wanted to remove special characters in swift string.
Like [, {, “, &, etc.
let regex = NSRegularExpression(pattern: ".*[^A-Za-z0-9].*", options: nil, error: nil)!
if regex.firstMatchInString(searchTerm!, options: nil, range: NSMakeRange(0, searchTerm!.length)) != nil {
println("could not handle special characters")
}
But this kind of solution only support the English Latin alphabets.
In these solutions, I have to write all the characters in the Regex
Above solutions was not suit with my case.
My Solution
This is my solution. You can use CharacterSet.punctuationCharacters
This is the output.
hello, (Nice to- meet 한국 école %&$you all. 123 ! Давай العربية 😀hello Nice to meet 한국 école $you all 123 Давай العربية 😀