简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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