Junz
Junz

Reputation: 3

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

I have a string that can contain unicode characters in the form of "\u{0026}" and I want it to be converted to its appropriate character "&".

How do I do that?

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

Thanks a lot!

Upvotes: 0

Views: 1012

Answers (2)

Ahmad F
Ahmad F

Reputation: 31665

In fact, I'm not familiar with what @MartinR suggested in his comment(s), it might be the solution for your issue...

However, you can simply achieve what are you trying to do by using the replacingOccurrences(of:with:) String method:

Returns a new string in which all occurrences of a target string in the receiver are replaced by another given string.

So, applied to your 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"

Hope it helped.

Upvotes: 0

OOPer
OOPer

Reputation: 47896

You may need to use regular expression:

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

I don't understand how you have gotten your input. But if you adopted some standard-based representation, you could get the expectedOutput more simply.

Upvotes: 0

Related Questions