How to remove special characters from string in Swift

Fredric Cliver
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  Давай العربية 😀

--

--

Fredric Cliver
Fredric Cliver

Written by Fredric Cliver

13+ years in the digital trenches. I decode complex tech concepts into actionable insights, focusing on AI, Software Engineering, and emerging technologies.

No responses yet