Skip to content

Instantly share code, notes, and snippets.

@squarefrog
Created February 27, 2020 13:39
Show Gist options
  • Save squarefrog/f7ddca8ac981f5dd33a7813f682288c8 to your computer and use it in GitHub Desktop.
Save squarefrog/f7ddca8ac981f5dd33a7813f682288c8 to your computer and use it in GitHub Desktop.
Regex warning.
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