tele
tele

Reputation: 31

How to remove special character from String in swift iOS

I need get value without special character from string

I tried this code but remove special character and letter

example :

var str = ".34!44fgf)(gg#$qwe3"
    str.components(separatedBy: CharacterSet.decimalDigits.inverted)//result => 34443

i am want results the following without special character => "3444fgfggqwe3"

Please Advise

Upvotes: 1

Views: 1141

Answers (2)

vadian
vadian

Reputation: 285072

Actually result is a huge array with a lot of empty strings.

This is another approach with Regular Expression

var str = ".34!44fgf)(gg#$qwe3"
str = str.replacingOccurrences(of: "[^[0-9a-zA-z]]", with: "", options: .regularExpression)

Upvotes: 0

Leo Dabus
Leo Dabus

Reputation: 236370

You can filter all characters that are letter or digits:

let result = str.filter { $0.isLetter || "0"..."9" ~= $0 }

print(result)   // "3444fgfggqwe3"

If you would like to restrict the letters to only lowercase letters from "a" to "z"

"a"..."z" ~= $0

or "A" to "Z"

"A"..."Z" ~= $0

Upvotes: 1

Related Questions