简体   繁体   English

快速转义的反斜杠无法按预期工作

[英]swift escaping backslash doesn't work as expected

When I print this: 当我打印此:

print("dfi:.*\\{8766370\\}.*:6582.*")

the result on the log looks as expected: 日志上的结果看起来像预期的那样:

>>>> dfi:.*\{8766370\}.*:6582.*

but when i construct the string dynamically the result looks wrong 但是当我动态构造字符串时,结果看起来是错误的

let re = "dfi:.*" + "\\" + "{" + "\(section)" + "\\" + "}" + ".*:\(feed).*"
print(re)

>>>> dfi:.*\\{8766370\\}.*:6582.*"

Notice that there is a double slash in the second case "\\" and I am not sure why. 请注意,第二种情况“ \\”中有一个双斜杠,但我不确定为什么。 I tried using a single or triple slash but it prints wrong still. 我尝试使用单斜线或三斜线,但仍然打印错误。

EDIT - Adding code: 编辑-添加代码:

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

You are literally printing everything inside of the array, which is going to show you the debugDescription variable, that is why you are seeing double slash. 您实际上是在打印数组内部的所有内容,这将向您显示debugDescription变量,这就是为什么看到双斜杠的原因。 It is printing the literal value of the string, not the interpolated value you want. 它正在打印字符串的文字值,而不是所需的插值。

If you want specific items in the array, you need to address the items inside of it by iterating through it, or addressing a certain index. 如果需要数组中的特定项目,则需要通过迭代数组或寻址某个索引来解决其中的项目。

Here is your code showing it is the description: 这是您的代码,它显示的是描述:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM