Created
September 19, 2016 18:39
-
-
Save psandeepunni/aee96f4935a5cbb5981cb866e9693b08 to your computer and use it in GitHub Desktop.
Hack/Parse Unicode Chars in Swift String with syntax \uXXXX
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
extension String { | |
func replaceUnicodeChars () -> String { | |
if self.rangeOfString("\\u") != nil { | |
let pattern = "u([A-F0-9]{4})" | |
do { | |
let regex = try NSRegularExpression(pattern: pattern, options: .DotMatchesLineSeparators) | |
let tmp = self as NSString | |
var results = [String]() | |
regex.enumerateMatchesInString(self, options: [], range: NSMakeRange(0, self.characters.count)) { result, flags, stop in | |
if let range = result?.rangeAtIndex(1) { | |
results.append(tmp.substringWithRange(range)) | |
} | |
} | |
let firstMatch = regex.firstMatchInString(self, options: [], range: NSMakeRange(0, self.characters.count)) | |
let finalLocation = (firstMatch?.range.location)! - 1; | |
let prefix = tmp.substringWithRange(NSMakeRange(0, finalLocation)); | |
var processedString = prefix + "" | |
for unicodeStr in results { | |
let num = Int(strtoul(unicodeStr, nil, 16)) | |
processedString = processedString + String(UnicodeScalar(num)) | |
} | |
print("NEW PROCESSED STRING === \(processedString)"); | |
return processedString | |
} catch let e as NSError { | |
print("\(e.localizedDescription)") | |
return self; | |
} | |
} else { | |
return self; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment