Advertisement
Larme

Untitled

Jul 28th, 2022
1,385
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.10 KB | None | 0 0
  1.     func parseCaptions(text: String) -> String {
  2.         let textRange = NSRange(location: 0, length: text.utf16.count) //NSRange, based on NSString use UTF16 for counting, while Swift.String use UTF8 by default, so `text.count` might be wrong
  3.         let regex = try! NSRegularExpression(pattern: "<text[^>]+>([^<]+)<\\/text>")
  4.         let matches = regex.matches(in: text, range: textRange)
  5.  
  6.         var result: String = text
  7.         for match in matches.reversed() {
  8.             let wholeNSRange = match.range
  9.             let wholeRange = Range(wholeNSRange, in: result)!
  10.             let textNSRange = match.range(at: 1)
  11.             let textRange = Range(textNSRange, in: result)!
  12.             var string = String(result[textRange])
  13.             string = string.replacingOccurrences(of: "\n", with: " ")
  14.             string = string.replacingOccurrences(of: "&#39;", with: "'")
  15.             string = string.replacingOccurrences(of: "&amp;quot;", with: "\"")
  16.             string.append("\n")
  17.             result = result.replacingCharacters(in: wholeRange, with: string)
  18.         }
  19.         return result
  20.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement