Advertisement
Guest User

Untitled

a guest
Sep 18th, 2018
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 0.68 KB | None | 0 0
  1. extension String {
  2.   func word(at index: Int) -> String {
  3.     do {
  4.       let regex = try NSRegularExpression(pattern: "([A-Z]|[a-z]|[0-9])\\w+", options: .caseInsensitive)
  5.  
  6.       let matches = regex.matches(in: self, options: .reportCompletion, range: NSRange(location: 0, length: self.count)).map { regexMatch -> Substring in
  7.         let range = regexMatch.range
  8.         return self[self.index(self.startIndex, offsetBy: range.location)..<self.index(self.startIndex, offsetBy: range.location + range.length)]
  9.       }
  10.  
  11.       guard matches.count > index else {
  12.         return ""
  13.       }
  14.  
  15.       return String(matches[index])
  16.     } catch let error {
  17.       return ""
  18.     }
  19.   }
  20. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement