Skip to content

Instantly share code, notes, and snippets.

@marklarr
Created June 3, 2014 06:53
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marklarr/d1032a1ffd493de8284c to your computer and use it in GitHub Desktop.
Save marklarr/d1032a1ffd493de8284c to your computer and use it in GitHub Desktop.
Ruby-esque regex in Swift
// Regex
import Foundation
operator infix =~ {}
@infix func =~ (str: String, pattern: String) -> Bool {
var error: NSError?
let regex = NSRegularExpression.regularExpressionWithPattern(pattern, options: nil, error: &error)
if (error) { return false }
return regex.numberOfMatchesInString(str, options: nil, range: NSMakeRange(0, countElements(str))) > 0
}
"Ayaka" =~ "^A.*" // true
"Ayaka" =~ "Mickey" // false
"Mark" =~ "M..k(ey)?" // true
@JJJayway
Copy link

JJJayway commented Jun 6, 2014

Nice.

Please note that overriding = instead of = will allow using Regexps in switch statements :-)
(Ref. "Expression Pattern" in The Swift Programming Language)

func ~=(pattern: String, value: String) -> Bool {
    return value =~ pattern
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment