Skip to content

Instantly share code, notes, and snippets.

@erica
Created October 30, 2017 19:42
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erica/19923524fc7ed26a75c74cafe2a37749 to your computer and use it in GitHub Desktop.
Save erica/19923524fc7ed26a75c74cafe2a37749 to your computer and use it in GitHub Desktop.
import Foundation
/// Provides NSRegularExpression pattern matching
/// against strings in `switch` and `~=` statements
public struct Regex {
public let regexPattern: String
public let options: NSRegularExpression.Options
/// Initialize a `Regex` instance that
/// defaults to no options. Update as needed for
/// case or diacritical insensitivity
///
/// - parameter regexPattern: The matching pattern
/// - parameter options: any `NSRegularExpression.Options`, defaulting to []
public init(_ regexPattern: String, _ options: NSRegularExpression.Options = []) {
(self.regexPattern, self.options) = (regexPattern, options)
}
/// Extends pattern matching to use the pattern and
/// options stored in the `Regex` matcher
public static func ~= (lhs: Regex, rhs: String) -> Bool {
guard let regex = try? NSRegularExpression(pattern: lhs.regexPattern, options: lhs.options)
else { return false }
let range = NSRange(location: 0, length: rhs.utf16.count)
if let _ = regex.firstMatch(in: rhs, range: range) { return true }
return false
}
}
// For example
let str = "Hello, playground"
str ~= "Hello" // false
str ~= "Hello, playground" // true
Regex("H.*o") ~= str // true
Regex("H.*o") ~= "Out of luck" // false
// matches
switch str {
case Regex("H.*o"): print("Hello to you!")
default: print("Nope")
}
// does not match
switch "Out of luck" {
case Regex("H.*o"): print("Hello to you!")
default: print("Nope")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment