快速转义反斜杠不能按预期工作

标签 swift xcode swift-string

当我打印这个时:

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
  }
}

关于快速转义反斜杠不能按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51198265/

相关文章:

ios - 自定义 UITextViewDelegate/UITextFieldDelegate 未调用

swift - 从两个容器 View 保存数据

ios - 如何限制我的应用程序仅适用于 iPhone,不包括 iPod touch?

swift - 什么是 String.Encoding.unicode?

swift - 为什么 Swift 的 String API 中包含 unicode 作为编码?

swift - 如何获得 Apple 表情符号名称而不是 Unicode 名称?

swift - 修改两个右侧 UIBarButtonItems 之间的间距

ios - “文档”无法转换为 'StitchTask<Document>' 。按照 mongo cloud atlas 上的说明进行操作后会弹出此错误

swift - 如何将一个 pickerview 用于多个文本字段?

ios - 未发现 Xcode swift 测试