[英]swift escaping backslash doesn't work as expected
當我打印此:
print("dfi:.*\\{8766370\\}.*:6582.*")
日志上的結果看起來像預期的那樣:
>>>> dfi:.*\{8766370\}.*:6582.*
但是當我動態構造字符串時,結果看起來是錯誤的
let re = "dfi:.*" + "\\" + "{" + "\(section)" + "\\" + "}" + ".*:\(feed).*"
print(re)
>>>> dfi:.*\\{8766370\\}.*:6582.*"
請注意,第二種情況“ \\”中有一個雙斜杠,但我不確定為什么。 我嘗試使用單斜線或三斜線,但仍然打印錯誤。
編輯-添加代碼:
for (section,feeds) in toPurge {
var regex = [String]()
for feed in feeds {
// dfi:\{(8767514|8769411|8768176)\}.*
let re = "dfi:.*" + "\\" + "{" + "\(section)" + "\\" + "}" + ".*:\(feed).*"
regex.append(re)
}
print(regex) // looks wrong ! bug in xcode?
for r in regex {
print(r) // looks perfect
}
}
您實際上是在打印數組內部的所有內容,這將向您顯示debugDescription
變量,這就是為什么看到雙斜杠的原因。 它正在打印字符串的文字值,而不是所需的插值。
如果需要數組中的特定項目,則需要通過迭代數組或尋址某個索引來解決其中的項目。
這是您的代碼,它顯示的是描述:
import Foundation
let toPurge = [(8767514,[6582])]
for (section,feeds) in toPurge {
var regex = [String]()
for feed in feeds {
// dfi:\{(8767514|8769411|8768176)\}.*
let re = "dfi:.*" + "\\" + "{" + "\(section)" + "\\" + "}" + ".*:\(feed).*"
regex.append(re)
print(re)
}
print(regex[0]) // correct
print(regex) // prints debugDescription
print(regex.debugDescription) // prints debugDescription
for r in regex {
print(r) // looks perfect
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.