我有一个字符串,其中可以包含“ \ 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

关于swift - 如何在Swift中将字符串“\u {0026}”转换为“&”?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41259153/

10-14 21:20
查看更多