Skip to content

Instantly share code, notes, and snippets.

@rogerluan
Last active July 27, 2020 02:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rogerluan/3ef1752ca22145aae4d85c431b5474d3 to your computer and use it in GitHub Desktop.
Save rogerluan/3ef1752ca22145aae4d85c431b5474d3 to your computer and use it in GitHub Desktop.
A few regex utilities in Swift.
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)
}
}
@rogerluan
Copy link
Author

Usage:

let regex = NSRegularExpression(#"^@?(\w){1,15}$"#) // Note the lack of `try!` before calling the initializer

let testString: String = "@rogerluan_"
if regex.matches(testString) {
    print("\(testString) matches the regex!)")
}

if testString ~= regex {
    print("\(testString) matches the regex!")
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment