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?
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"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With