5

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?

MarksCode
  • 8,074
  • 15
  • 64
  • 133

1 Answers1

8

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")) 
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563