[+] Encapsulate Regex matching stuff

This commit is contained in:
Hykilpikonna
2021-01-22 15:02:05 -05:00
parent 9ee1132d7d
commit 788eb4973a
+27
View File
@@ -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
}
}