Advertisement
Guest User

Untitled

a guest
Apr 25th, 2015
217
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. class Regex {
  2. let pattern: String
  3. let options: NSRegularExpressionOptions!
  4.  
  5. private var matcher: NSRegularExpression {
  6. return NSRegularExpression(pattern: self.pattern, options: nil, error: nil)
  7. }
  8.  
  9. required init(pattern: String, options: NSRegularExpressionOptions = nil) {
  10. self.pattern = pattern
  11. self.options = options
  12. }
  13.  
  14. func match(string: String, options: NSMatchingOptions = nil) -> Bool {
  15. return self.matcher.numberOfMatchesInString(string, options: options, range: NSMakeRange(0, string.utf16Count)) != 0
  16. }
  17. }
  18.  
  19. extension Regex: StringLiteralConvertible, ExtendedGraphemeClusterLiteralConvertible {
  20. typealias ExtendedGraphemeClusterLiteralType = StringLiteralType
  21.  
  22. class func convertFromExtendedGraphemeClusterLiteral(value: ExtendedGraphemeClusterLiteralType) -> Self {
  23. return self(pattern: value)
  24. }
  25.  
  26. class func convertFromStringLiteral(value: StringLiteralType) -> Self {
  27. return self(pattern: value)
  28. }
  29. }
  30.  
  31. // MARK: -
  32.  
  33. protocol RegularExpressionMatchable {
  34. func match(regex: Regex) -> Bool
  35. }
  36.  
  37. infix operator =~ { associativity left precedence 130 }
  38. func =~<T: RegularExpressionMatchable> (left: T, right: Regex) -> Bool {
  39. return left.match(right)
  40. }
  41.  
  42. extension String: RegularExpressionMatchable {
  43. func match(regex: Regex) -> Bool {
  44. return regex.match(self)
  45. }
  46. }
  47.  
  48.  
  49. "foo" =~ "f" // true
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement