2

当我打印这个:

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

1 回答 1

0

您实际上是在打印数组内的所有内容,这将向您显示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
  }
}
于 2018-07-05T19:29:13.860 回答