Created
June 8, 2014 05:05
-
-
Save JimRoepcke/d68dd41ee2fedc6a0c67 to your computer and use it in GitHub Desktop.
Regex operator
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
// Playground - noun: a place where people can play | |
import Cocoa | |
struct Regex { | |
let pattern: String | |
let expressionOptions: NSRegularExpressionOptions | |
let matchingOptions: NSMatchingOptions | |
init(pattern: String, expressionOptions: NSRegularExpressionOptions, matchingOptions: NSMatchingOptions) { | |
self.pattern = pattern | |
self.expressionOptions = expressionOptions | |
self.matchingOptions = matchingOptions | |
} | |
init(pattern:String) { | |
self.pattern = pattern | |
expressionOptions = NSRegularExpressionOptions(0) | |
matchingOptions = NSMatchingOptions(0) | |
} | |
} | |
let r1 = Regex(pattern: "[a-z]") | |
let r2 = Regex(pattern: "[0-9]", expressionOptions: NSRegularExpressionOptions(0), matchingOptions: NSMatchingOptions(0)) | |
operator infix =~ { associativity left precedence 140 } | |
func =~(left: String, right: Regex) -> Bool { | |
let range: NSRange = NSMakeRange(0, countElements(left)) | |
if let regex = NSRegularExpression.regularExpressionWithPattern(right.pattern, options: right.expressionOptions, error: nil) { | |
let matches: AnyObject[] = regex.matchesInString(left, options: right.matchingOptions, range: range) | |
return matches.count > 0 | |
} else { | |
"wat" | |
} | |
return false | |
} | |
func =~(left: String, right: String) -> Bool { | |
return left =~ Regex(pattern: right) | |
} | |
"a" =~ r1 | |
"2" =~ r1 | |
"a" =~ r2 | |
"2" =~ r2 | |
"2" =~ "[a-z]" | |
"2" =~ "[0-9]" |
Awesome, thank you!
I added this and a "not match" operator (!=~) to SwiftVerbalExpressions: https://github.com/VerbalExpressions/SwiftVerbalExpressions
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Love this so much! We've extended it to be a little more performant if the regex is re-used and added a template replacement operator too: http://www.swift-studies.com/blog/2014/6/12/regex-matching-and-template-replacement-operators-in-swift