Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unescaping backslash in Swift

Tags:

string

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

like image 554
1024jp Avatar asked Sep 14 '16 10:09

1024jp


1 Answers

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!
like image 114
kabiroberai Avatar answered Sep 22 '22 14:09

kabiroberai