2017-03-10 11 views
2

我試圖使用String.replacingOccurrences更改下列字符的所有匹配到逗號:更換出現迅速的正則表達式

#.$[]

不過,我似乎無法得到它的什麼做到這一點我有:

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

print(cleanStr(str: "me[[email protected]#l.co$m")) // prints "me[[email protected],l,co,m\n" 

有人能幫我看看我做錯了什麼嗎?

回答

3

在你的模式,[.#$[/]],有字符類工會,也就是說,它只匹配.#$/字符(2字符類,[.#$][/]的組合)。

在ICU正則表達式,你需要逃避字面方括號[]字符類中:

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

此代碼輸出me,[email protected],l,co,m

func cleanStr(str: String) -> String { 
    return str.replacingOccurrences(of: "[.#$\\[/\\]]", with: ",", options: [.regularExpression]) 
} 
print(cleanStr(str: "me[[email protected]#l.co$m")) 
+0

你我的好先生,是一個該死天才。天才! – MarksCode