Skip to content

Instantly share code, notes, and snippets.

@TerryCK
Created May 24, 2018 11:13
Show Gist options
  • Save TerryCK/9005c4fd3366d1b94257d71232c5a4b3 to your computer and use it in GitHub Desktop.
Save TerryCK/9005c4fd3366d1b94257d71232c5a4b3 to your computer and use it in GitHub Desktop.
import Foundation
extension NSRegularExpression {
convenience init(_ pattern: String) {
do {
try self.init(pattern: pattern)
} catch {
preconditionFailure("Illeagal regular expression: \(pattern).")
}
}
func matches(_ string: String) -> Bool {
let range = NSRange(location: 0, length: string.utf16.count)
return firstMatch(in: string, options: [], range: range) != nil
}
}
let testString = "hat"
let range = NSRange(location: 0, length: testString.utf16.count)
let regex = NSRegularExpression("[a-z]at")
regex.firstMatch(in: testString, options: [], range: range) != nil
regex.matches("xxat")
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
}
}
"https://" ~= "^.*://$"
"cad" ~= "ca[a-z]*d"
"cad" ~= "ca[a-z]+d"
"cad" ~= "ca[a-z]?d"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment