我需要添加反斜杠(转义)所有特殊符号,例如
(,),+,[,]
示例:
extension String {
var escaping: String {
return self.replacing(/[()+]/, with: "\\($0)")
}
}
let text = "Hello everyone!)) + another one day"
print(text.escaping)
所以我需要得到结果:
"Hello everyone!\)\) \+ another one day"
有什么办法可以用 swift 中的正则表达式来做到这一点吗?不使用
replacingOccurrences(of
。
var escaping: String {
return self.replacingOccurrences(of: ".", with: "\\.")
.replacingOccurrences(of: "-", with: "\\-")
.replacingOccurrences(of: "_", with: "\\_")
.replacingOccurrences(of: ")", with: "\\)")
.replacingOccurrences(of: "(", with: "\\(")
.replacingOccurrences(of: "(", with: "\\(")
.replacingOccurrences(of: "+", with: "\\+")
.replacingOccurrences(of: "!", with: "\\!")
.replacingOccurrences(of: "[", with: "\\[")
.replacingOccurrences(of: "]", with: "\\]")
.replacingOccurrences(of: "=", with: "\\=")
.replacingOccurrences(of: "|", with: "\\|")
.replacingOccurrences(of: "{", with: "\\{")
.replacingOccurrences(of: "}", with: "\\}")
}