代码之家  ›  专栏  ›  技术社区  ›  Avba

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

  •  2
  • Avba  · 技术社区  · 8 年前

    当我打印时:

    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
      }
    }
    
    1 回复  |  直到 8 年前
        1
  •  0
  •   Knight0fDragon    8 年前

    你正在打印数组中的所有内容,这将显示 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
      }
    }