如何将Swift中的字符串“\u{0026}”转换为“&”?

How do I convert a string of "\u{0026}" to "&" in Swift?

我有一个可以包含“\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 在他的评论中提出的建议,这可能是您问题的解决方案...

但是,您可以使用 replacingOccurrences(of:with:) 字符串方法简单地实现您想要做的事情:

Returns a new string in which all occurrences of a target string in the receiver are replaced by another given 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"

希望对您有所帮助。