From 788eb4973a0715e57a9432ea249a26a233854fc6 Mon Sep 17 00:00:00 2001 From: Hykilpikonna Date: Fri, 22 Jan 2021 15:02:05 -0500 Subject: [PATCH] [+] Encapsulate Regex matching stuff --- ProjectClock/Utils.swift | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/ProjectClock/Utils.swift b/ProjectClock/Utils.swift index 28b9bd1..a41641e 100644 --- a/ProjectClock/Utils.swift +++ b/ProjectClock/Utils.swift @@ -119,3 +119,30 @@ extension UIViewController self.present(alert, animated: true, completion: nil) } } + + +/// Regex Matching (Credit: https://www.hackingwithswift.com/articles/108/how-to-use-regular-expressions-in-swift) +extension NSRegularExpression +{ + convenience init(_ pattern: String) + { + do { try self.init(pattern: pattern) } + catch { preconditionFailure("Illegal 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 + } +} + +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 + } +}