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?

1 Answer 1

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")) 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.