NSRegularExpression+SSK.swift 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. //
  2. // Copyright (c) 2019 Open Whisper Systems. All rights reserved.
  3. //
  4. import Foundation
  5. @objc
  6. public extension NSRegularExpression {
  7. @objc
  8. public func hasMatch(input: String) -> Bool {
  9. return self.firstMatch(in: input, options: [], range: NSRange(location: 0, length: input.utf16.count)) != nil
  10. }
  11. @objc
  12. public class func parseFirstMatch(pattern: String,
  13. text: String,
  14. options: NSRegularExpression.Options = []) -> String? {
  15. do {
  16. let regex = try NSRegularExpression(pattern: pattern, options: options)
  17. guard let match = regex.firstMatch(in: text,
  18. options: [],
  19. range: NSRange(location: 0, length: text.utf16.count)) else {
  20. return nil
  21. }
  22. let matchRange = match.range(at: 1)
  23. guard let textRange = Range(matchRange, in: text) else {
  24. owsFailDebug("Invalid match.")
  25. return nil
  26. }
  27. let substring = String(text[textRange])
  28. return substring
  29. } catch {
  30. Logger.error("Error: \(error)")
  31. return nil
  32. }
  33. }
  34. @objc
  35. public func parseFirstMatch(inText text: String,
  36. options: NSRegularExpression.Options = []) -> String? {
  37. guard let match = self.firstMatch(in: text,
  38. options: [],
  39. range: NSRange(location: 0, length: text.utf16.count)) else {
  40. return nil
  41. }
  42. let matchRange = match.range(at: 1)
  43. guard let textRange = Range(matchRange, in: text) else {
  44. owsFailDebug("Invalid match.")
  45. return nil
  46. }
  47. let substring = String(text[textRange])
  48. return substring
  49. }
  50. }