我有一个可以包含“\u{0026}”形式的 unicode 字符的字符串,我希望将其转换为相应的字符“&”。
我怎么做?
let input = "\\u{0026} something else here"
let expectedOutput = "& something else here"
非常感谢!
我有一个可以包含“\u{0026}”形式的 unicode 字符的字符串,我希望将其转换为相应的字符“&”。
我怎么做?
let input = "\\u{0026} something else here"
let expectedOutput = "& something else here"
非常感谢!
您可能需要使用正则表达式:
class StringEscpingRegex: NSRegularExpression {
override func replacementString(for result: NSTextCheckingResult, in string: String, offset: Int, template templ: String) -> String {
let nsString = string as NSString
if
result.numberOfRanges == 2,
case let capturedString = nsString.substring(with: result.rangeAt(1)),
let codePoint = UInt32(capturedString, radix: 16),
codePoint != 0xFFFE, codePoint != 0xFFFF, codePoint <= 0x10FFFF,
codePoint<0xD800 || codePoint > 0xDFFF
{
return String(Character(UnicodeScalar(codePoint)!))
} else {
return super.replacementString(for: result, in: string, offset: offset, template: templ)
}
}
}
let pattern = "\\\\u\\{([0-9A-Fa-f]{1,6})\\}"
let regex = try! StringEscpingRegex(pattern: pattern)
let input = "\\u{0026} something else here"
let expectedOutput = "& something else here"
let actualOutput = regex.stringByReplacingMatches(in: input, range: NSRange(0..<input.utf16.count), withTemplate: "?")
assert(actualOutput == expectedOutput) //assertion succeeds
我不明白你是如何得到你的input
. 但是如果你采用一些基于标准的表示,你可以得到expectedOutput
更简单的。
事实上,我不熟悉@MartinR在他的评论中提出的建议,这可能是您问题的解决方案......
但是,您可以通过使用replacementOccurrences(of:with:) String 方法简单地实现您想要做的事情:
返回一个新字符串,其中接收器中所有出现的目标字符串都被另一个给定的字符串替换。
因此,应用于您的字符串:
let input = "\\u{0026} something else here"
let output1 = input.replacingOccurrences(of: "\\u{0026}", with: "\u{0026}") // "& something else here"
// OR...
let output2 = input.replacingOccurrences(of: "\\u{0026}", with: "&") // "& something else here"
希望它有所帮助。