【问题标题】:swift escaping backslash doesn't work as expected快速转义反斜杠无法按预期工作
【发布时间】:2018-07-05 19:03:37
【问题描述】:

当我打印这个时:

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

【问题讨论】:

  • 当我在这里运行你的代码时,我得到了正确的结果:online.swiftplayground.run
  • 你确定吗?在 Playground 中,结果列显示两个反斜杠,但控制台打印一个
  • let section = 8766370 let feed = 6582 let re = "dfi:.*" + "\\" + "{" + "\(section)" + "\\" + "}" + ".*:\(feed).*" print(re)
  • dfi:.*\{8766370\}.*:6582.*
  • 你正在打印一个数组的全部内容,这就是为什么你得到双斜杠(注意括号)你需要打印正则表达式[0]

标签: swift xcode swift-string


【解决方案1】:

您实际上是在打印数组内的所有内容,这将向您显示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
  }
}

【讨论】:

  • 在每个元素上打印一个数组调用 debugDescription,而 that 是显示所有特殊字符的转义序列(如双反斜杠)。 description 不会那样做。
  • @MartinR 我改变了我的答案以反映这一点,因为它打印debugDescription 更有意义,但描述也打印文字字符串而不是插值字符串(我之前提供的代码编辑表明它正在这样做)
  • 问题(据我所知)是关于如何打印字符串中的反斜杠,而不是关于字符串插值。试试let s = "a\\b" ; print(s.description) ; print(s.debugDescription)
  • @MartinR 是的,但你需要更深入地挖掘,你会看到他实际上是在打印一个数组,而不是一个字符串。我猜他是在迷惑自己。我看到的问题是“为什么我的变量没有按预期打印?”不是“为什么字符串没有按我的预期打印?”
猜你喜欢
  • 1970-01-01
  • 2011-09-19
  • 1970-01-01
  • 2015-05-19
  • 2015-09-21
  • 2011-11-09
  • 2017-04-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多