skip to Main Content

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: "\}")
    }

Related: Telegram does not escape some markdown characters

2

Answers


  1. 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.

    extension String {
        var escaping: String {
            self.replacing(/[()+.-_![]=|{}]/) { match in "\" + match.output }
        }
    }
    

    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 (?)

    Login or Signup to reply.
  2. 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 signature

    func replacing<Output, Replacement>(
        _ regex: some RegexComponent,
        subrange: Range<Self.Index>,
        maxReplacements: Int = .max,
        with replacement: (Regex<Output>.Match) throws -> Replacement
    ) rethrows -> Self where Replacement : Collection, Replacement.Element == Character
    

    Here’s an example of how to use it

    let text = "Hello everyone!))( + another one day"
    let replacement = text.replacing(/([()+])/, subrange: text.startIndex ..< text.endIndex) { 
        match in
        "\" + match.1 
    }
    print(replacement)
    
    

    Prints

    Hello everyone!))( + another one day
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search