Skip to content

Instantly share code, notes, and snippets.

@JimRoepcke
Created June 8, 2014 05:05
Show Gist options
  • Star 24 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save JimRoepcke/d68dd41ee2fedc6a0c67 to your computer and use it in GitHub Desktop.
Save JimRoepcke/d68dd41ee2fedc6a0c67 to your computer and use it in GitHub Desktop.
Regex operator
// 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]"
@RougeExciter
Copy link

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

@nubbel
Copy link

nubbel commented Jun 12, 2014

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