Last active
July 24, 2019 09:35
-
-
Save zakbarlow1995/4850d7723989958c29ba5951d1445bd3 to your computer and use it in GitHub Desktop.
String extension to add a regex comparison operator "~="
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 | |
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 | |
} | |
} |
Example usage, checking a(n error) string to see if it contains a HTTP status code:
extension String {
func contains(statusCode: StatusCode) -> Bool {
return self ~= "\\b\(statusCode.rawValue)[0-9][0-9]\\b"
}
}
enum StatusCode: Int, CaseIterable {
case oneHundred = 1, twoHundred, threeHundred, fourHundred, fiveHundred
}
Usage:
// Thrown error contains status code 400-499
if errorString.contains(statusCode: .fourHundred) {
// Do something...
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Credit: https://www.hackingwithswift.com/articles/108/how-to-use-regular-expressions-in-swift