Created
August 11, 2014 18:08
-
-
Save mattt/2099ee21bbfbebaa94a3 to your computer and use it in GitHub Desktop.
Creating a regular expression object from a String literal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Regex { | |
let pattern: String | |
let options: NSRegularExpressionOptions! | |
private var matcher: NSRegularExpression { | |
return NSRegularExpression(pattern: self.pattern, options: nil, error: nil) | |
} | |
required init(pattern: String, options: NSRegularExpressionOptions = nil) { | |
self.pattern = pattern | |
self.options = options | |
} | |
func match(string: String, options: NSMatchingOptions = nil) -> Bool { | |
return self.matcher.numberOfMatchesInString(string, options: options, range: NSMakeRange(0, string.utf16Count)) != 0 | |
} | |
} | |
extension Regex: StringLiteralConvertible, ExtendedGraphemeClusterLiteralConvertible { | |
typealias ExtendedGraphemeClusterLiteralType = StringLiteralType | |
class func convertFromExtendedGraphemeClusterLiteral(value: ExtendedGraphemeClusterLiteralType) -> Self { | |
return self(pattern: value) | |
} | |
class func convertFromStringLiteral(value: StringLiteralType) -> Self { | |
return self(pattern: value) | |
} | |
} | |
// MARK: - | |
protocol RegularExpressionMatchable { | |
func match(regex: Regex) -> Bool | |
} | |
infix operator =~ { associativity left precedence 130 } | |
func =~<T: RegularExpressionMatchable> (left: T, right: Regex) -> Bool { | |
return left.match(right) | |
} | |
extension String: RegularExpressionMatchable { | |
func match(regex: Regex) -> Bool { | |
return regex.match(self) | |
} | |
} | |
"foo" =~ "f" // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hi I update it for swift 1.2 https://gist.github.com/SuperMarioBean/38a5255fc1b14fb74739