Skip to content

Instantly share code, notes, and snippets.

@chrismsimpson
Last active September 28, 2019 05:49
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 chrismsimpson/a8df2409f898af9e9d4c to your computer and use it in GitHub Desktop.
Save chrismsimpson/a8df2409f898af9e9d4c to your computer and use it in GitHub Desktop.
Regex Helpers for Swift
import Foundation
public struct Regex {
private let expression: NSRegularExpression
private let pattern: String
public init?(pattern _pattern: String) {
self.pattern = _pattern
do {
self.expression = try NSRegularExpression(
pattern: self.pattern,
options: .caseInsensitive)
}
catch {
return nil
}
}
public func matches(in input: String) -> Bool {
guard let range = NSRange(input), let matches = self.expression.matches(in: input, options: [], range: range) else {
return false
}
return matches
}
}
extension String {
public func matches(pattern: String) -> Bool {
guard let regex = Regex(pattern: pattern) else {
return false
}
return regex.matches(in: self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment