Guest User

Untitled

a guest
Oct 20th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. import Foundation
  2.  
  3. struct Regex {
  4. let pattern: String
  5. }
  6.  
  7. protocol Matchable : StringProtocol {
  8. var regex: Regex { get }
  9. func matches(regex: Regex, options: NSRegularExpression.Options) -> [String]
  10. func captureGroups(regex: Regex, options: NSRegularExpression.Options) -> [String]
  11. }
  12.  
  13. extension Matchable {
  14. var regex: Regex { return Regex(pattern: String(self)) }
  15. }
  16.  
  17. extension String: Matchable {
  18.  
  19. func capturedGroups(regex: Regex, options: NSRegularExpression.Options = []) -> [String] {
  20. return Array(matches(regex: regex, options: options)[1...])
  21. }
  22.  
  23. func matches(regex: Regex, options: NSRegularExpression.Options = []) -> [String] {
  24. guard let match = (try? NSRegularExpression(pattern: regex.pattern, options: options))?.firstMatch(in: self, options: [], range: NSRange(startIndex..., in: self)) else { return [] }
  25. return (0..<match.numberOfRanges).flatMap {
  26. return match.range(at: $0).location == NSNotFound ? nil : Range(match.range(at: $0), in: self).flatMap { String(self[$0]) }
  27. }
  28.  
  29. }
  30. }
  31.  
  32. "hi hello".capturedGroups(regex: "(\\w*)\\s(\\w*)".regex) // ["hi", "hello"]
  33. "hi hello".matches(regex: "(\\w*)\\s(\\w*)".regex) // ["hi hello", "hi", "hello"]
Add Comment
Please, Sign In to add comment