Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping backslash in Swift

I'm sending regular expressions to CloudKit as a String value and it doesn't seem to like it, replacing \\by \. However, once I'm getting this value from my app I would like to retransform it in its original form, with \\instead of \.

I don't know how to manage this kind of escaped characters in Swift because I cannot even set a String with a \ in my code but I'm still able to manage them when getting them from CloudKit. Here is an example of String:

var onlyOneBackslash: String = valueFromCloudKit
print(onlyOneBackslash) // booking\.com

How to escape the backslash to transform booking\.com into booking\\.com?

like image 947
Armand Grillet Avatar asked Aug 20 '15 13:08

Armand Grillet


People also ask

How do you unescape a string in Swift?

Escaping backslashes is easily done with NSRegularExpression. escapedTemplate(for: "\\n") . This returns "\\\\n" as expected.

What is raw strings in Swift?

Raw strings (denoted by starting and ending pound symbols ( # ) before and after the quotation marks), allow us to create strings that will print exactly what you see. As you know, there are certain escape sequences that can make our strings print differently.


1 Answers

The double backslash exists only in your code, it is a convention of the compiler. It never exists in the string itself, just in the Swift code.

If you want a double backslash in the string you need to have four backslashes in your code. Or use a String method to replace single backslashes with double backslashes.

Code example:

let originalString = "1\\2"
print("originalString: \(originalString)")
let newString = originalString.stringByReplacingOccurrencesOfString("\\", withString: "\\\\", options: .LiteralSearch, range: nil)
print("newString: \(newString)")

Output:

originalString: 1\2  
newString: 1\\2  
like image 62
zaph Avatar answered Sep 22 '22 06:09

zaph