Guest User

Untitled

a guest
May 27th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. Swift 3 (Xcode 8)
  2. ```swift
  3. func matches(for regex: String, in text: String) -> [String] {
  4.  
  5. do {
  6. let regex = try NSRegularExpression(pattern: regex)
  7. let nsString = text as NSString
  8. let results = regex.matches(in: text, range: NSRange(location: 0, length: nsString.length))
  9. return results.map { nsString.substring(with: $0.range)}
  10. } catch let error {
  11. print("invalid regex: \(error.localizedDescription)")
  12. return []
  13. }
  14. }
  15. ```
  16. Example:
  17.  
  18. ```swift
  19. let string = "🇩🇪€4€9"
  20. let matched = matches(for: "[0-9]", in: string)
  21. print(matched)
  22. // ["4", "9"]
  23. ```
  24.  
  25. ---
  26. As of Swift 4 (Xcode 9), the Swift standard library provides functions to convert between Range<String.Index> and NSRange.
  27.  
  28. ```
  29. func matches(for regex: String, in text: String) -> [String] {
  30.  
  31. do {
  32. let regex = try NSRegularExpression(pattern: regex)
  33. let results = regex.matches(in: text,
  34. range: NSRange(text.startIndex..., in: text))
  35. return results.map {
  36. String(text[Range($0.range, in: text)!])
  37. }
  38. } catch let error {
  39. print("invalid regex: \(error.localizedDescription)")
  40. return []
  41. }
  42. }
  43. ```
  44.  
  45. Example:
  46.  
  47. ```
  48. let string = "🇩🇪€4€9"
  49. let matched = matches(for: "[0-9]", in: string)
  50. print(matched)
  51. // ["4", "9"]
  52. ```
  53.  
  54. Note: The forced unwrap Range($0.range, in: text)! is safe because the NSRange refers to a substring of the given string text. However, if you want to avoid it then use
  55.  
  56. ```
  57. return results.flatMap {
  58. Range($0.range, in: text).map { String(text[$0]) }
  59. }
  60. ```
  61.  
  62. extension String
  63. {
  64. func hashtags() -> [String]
  65. {
  66. if let regex = try? NSRegularExpression(pattern: "#[a-z0-9]+", options: .caseInsensitive)
  67. {
  68. let string = self as NSString
  69.  
  70. return regex.matches(in: self, options: [], range: NSRange(location: 0, length: string.length)).map {
  71. string.substring(with: $0.range).replacingOccurrences(of: "#", with: "").lowercased()
  72. }
  73. }
  74.  
  75. return []
  76. }
  77. }
Add Comment
Please, Sign In to add comment