Last active
September 28, 2019 05:49
-
-
Save chrismsimpson/a8df2409f898af9e9d4c to your computer and use it in GitHub Desktop.
Regex Helpers for Swift
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 | |
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