Created
February 27, 2020 13:39
-
-
Save squarefrog/f7ddca8ac981f5dd33a7813f682288c8 to your computer and use it in GitHub Desktop.
Regex warning.
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 | |
// from https://www.hackingwithswift.com/articles/108/how-to-use-regular-expressions-in-swift | |
extension String { | |
static func ~= (lhs: String, rhs: String) -> Bool { | |
guard let regex = try? NSRegularExpression(pattern: rhs) else { return false } | |
let range = NSRange(location: 0, length: lhs.utf16.count) | |
return regex.firstMatch(in: lhs, options: [], range: range) != nil | |
} | |
} | |
// Notice how applying the extension overrides the natural behaviour of `case`. | |
// Run this in a playground, then comment out the extension and compare the results. | |
switch "hello" { | |
case "hello world": | |
print("'Hello' matches 'Hello world'!") | |
default: | |
print("'Hello' doesn't match 'Hello world'. All is well.") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment