Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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