Last active
July 27, 2020 02:51
-
-
Save rogerluan/3ef1752ca22145aae4d85c431b5474d3 to your computer and use it in GitHub Desktop.
A few regex utilities in Swift.
This file contains hidden or 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
extension NSRegularExpression { | |
convenience init(_ pattern: String) { | |
do { | |
try self.init(pattern: pattern) | |
} catch { | |
preconditionFailure("Illegal regular expression with pattern: \(pattern)") | |
} | |
} | |
func matches(_ string: String, options: NSRegularExpression.MatchingOptions = []) -> Bool { | |
let range = NSRange(location: 0, length: string.utf16.count) | |
return firstMatch(in: string, options: options, range: range) != nil | |
} | |
} | |
extension String { | |
static func ~= (lhs: String, rhs: String) -> Bool { | |
guard let regex = try? NSRegularExpression(pattern: rhs) else { return false } | |
return regex.matches(lhs) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: