Search code examples
swiftstring

Unescaping backslash in Swift


I wanna unescape backslashes in user input strings to use them for regex replacement.

Escaping backslashes is easily done with NSRegularExpression.escapedTemplate(for: "\\n"). This returns "\\\\n" as expected. However how can I backward transform them, for example, like \\n (backslash + n) to \n (return)?


Solution

  • I don't think it is possible to do this automatically, however, as there are only a few escaped characters in Swift, you can put them into an array, loop through them, and then replace all instances with the unescaped version. Here's a String extension I made that does this:

    extension String {
        var unescaped: String {
            let entities = ["\0", "\t", "\n", "\r", "\"", "\'", "\\"]
            var current = self
            for entity in entities {
                let descriptionCharacters = entity.debugDescription.characters.dropFirst().dropLast()
                let description = String(descriptionCharacters)
                current = current.replacingOccurrences(of: description, with: entity)
            }
            return current
        }
    }
    

    To use it, simply access the property. For example,

    print("Hello,\\nWorld!".unescaped) 
    

    will print

    Hello,
    World!