I need to add backslash (escape) all special symbols, like (,),+,[,]
Example:
extension String {
var escaping: String {
return self.replacing(/[()+]/, with: "\($0)")
}
}
let text = "Hello everyone!)) + another one day"
print(text.escaping)
So I need to have in result:
"Hello everyone!)) + another one day"
Is there any way to do this with regex in swift? Without using 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: "\}")
}
2
Answers
You can use the
replacing
overload that takes a closure(Regex<Output>.Match) -> Replacement
, to access the match result, so you can use the match result as part of the replacement.Note that you should escape
-
,[
, and]
in the character class.Also consider putting
in the character class. Surely you want to escape that as well (?)
There’s a version of
replacing(_:subrange:maxReplacements:with:)
which takes a closure so you can construct a replacement string from the match. This is its signatureHere’s an example of how to use it
Prints