如何将字符串“\ u {0026}”转换为“&”在斯威夫特?

时间:2016-12-21 09:23:31

标签: swift unicode unicode-literals

我有一个字符串,可以包含“\ u {0026}”形式的unicode字符,我希望将其转换为适当的字符“&”。

我该怎么做?

let input = "\\u{0026} something else here"
let expectedOutput = "& something else here"

非常感谢!

2 个答案:

答案 0 :(得分:0)

您可能需要使用正则表达式:

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

答案 1 :(得分:0)

事实上,我不熟悉他的评论中提出的@MartinR内容,它可能是您问题的解决方案......

但是,您可以使用replacingOccurrences(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"

希望它有所帮助。