1024jp 1024jp - 6 months ago 38
Swift Question

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
as expected. However how can I backward transform them, for example, like
(backslash + n) to


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,


will print