Created
October 30, 2017 19:42
-
-
Save erica/19923524fc7ed26a75c74cafe2a37749 to your computer and use it in GitHub Desktop.
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
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