Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace occurrences swift regex

I'm trying to use the String.replacingOccurrences to change all occurrences of the following characters into commas:

#.$[]

However I can't seem to get it to accomplish this with what I have:

func cleanStr(str: String) -> String {
    return str.replacingOccurrences(of: "[.#$[/]]", with: ",", options: [.regularExpression])
}

print(cleanStr(str: "me[ow@gmai#l.co$m"))   // prints "me[ow@gmai,l,co,m\n"

Can anybody help me see what I'm doing wrong?

like image 418
MarksCode Avatar asked Mar 10 '23 16:03

MarksCode


1 Answers

In your pattern, [.#$[/]], there is a character class union, that is, it only matches ., #, $ and / characters (a combination of two character classes, [.#$] and [/]).

In ICU regex, you need to escape literal square brackets [ and ] inside a character class:

"[.#$\\[/\\]]"

This code outputs me,ow@gmai,l,co,m:

func cleanStr(str: String) -> String {
    return str.replacingOccurrences(of: "[.#$\\[/\\]]", with: ",", options: [.regularExpression])
}
print(cleanStr(str: "me[ow@gmai#l.co$m")) 
like image 89
Wiktor Stribiżew Avatar answered Mar 19 '23 17:03

Wiktor Stribiżew