在Swift中转义反斜杠 [英] Escaping backslash in Swift
问题描述
我正在将正则表达式作为字符串值发送给CloudKit,并且似乎不喜欢它,将 \\
替换为 \
。但是,一旦我从我的应用程序中获取这个值,我想以原来的形式,以 \\
而不是 \\ \\
。
我不知道如何在Swift中管理这种转义的字符,因为我甚至不能使用 \
我的代码,但我仍然能够管理他们从CloudKit得到他们。这是一个String的例子:
var onlyOneBackslash:String = valueFromCloudKit
print(onlyOneBackslash)// booking\ .com
如何将反斜杠转义为转换 booking\.com
into booking\\.com
?
双重反斜杠仅存在于代码中,这是编译器的惯例。它不会存在于字符串本身,只是在Swift代码中。
如果您希望在字符串中使用双反斜杠,则需要在代码中有四个反斜杠。或者使用String方法用双反斜杠替换单个反斜杠。
代码示例:
code> let originalString =1\\\2
print(originalString:\(originalString))
let newString = originalString.stringByReplacingOccurrencesOfString(\\ withString:\\\\\,选项:.LiteralSearch,range:nil)
print(newString:\(newString))
/ pre>
输出:
originalString:1\2
newString:1\\\2
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
intobooking\\.com
?解决方案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
这篇关于在Swift中转义反斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!