我有一個字符串,可以包含「\ u」的形式的Unicode字符,我希望它被轉換爲適當的字符「&」。如何在Swift中將字符串「 u」替換爲「&」?
我該怎麼做?
let input = "\\u{0026} something else here"
let expectedOutput = "& something else here"
非常感謝!
我有一個字符串,可以包含「\ u」的形式的Unicode字符,我希望它被轉換爲適當的字符「&」。如何在Swift中將字符串「 u」替換爲「&」?
我該怎麼做?
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在他的評論(縣),它可能是你的問題的解決建議...
但是,你可以簡單地實現你到底通過使用replacingOccurrences(of:with:)字符串的方法做:
返回其在 接收目標字符串的所有出現由另一指定字符串替換一個新的字符串。
因此,適用於您的字符串:
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"
希望它幫助。
''\ u \ n其他的地方在這裏''日誌「&其他在這裏」。有什麼問題? –
進行編輯以添加額外的反斜槓。感謝您指出 – Junz
字符串從哪裏來? *爲什麼*是這樣編碼的? –