Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Foundation
- struct Regex {
- let pattern: String
- }
- protocol Matchable : StringProtocol {
- var regex: Regex { get }
- func matches(regex: Regex, options: NSRegularExpression.Options) -> [String]
- func captureGroups(regex: Regex, options: NSRegularExpression.Options) -> [String]
- }
- extension Matchable {
- var regex: Regex { return Regex(pattern: String(self)) }
- }
- extension String: Matchable {
- func capturedGroups(regex: Regex, options: NSRegularExpression.Options = []) -> [String] {
- return Array(matches(regex: regex, options: options)[1...])
- }
- func matches(regex: Regex, options: NSRegularExpression.Options = []) -> [String] {
- guard let match = (try? NSRegularExpression(pattern: regex.pattern, options: options))?.firstMatch(in: self, options: [], range: NSRange(startIndex..., in: self)) else { return [] }
- return (0..<match.numberOfRanges).flatMap {
- return match.range(at: $0).location == NSNotFound ? nil : Range(match.range(at: $0), in: self).flatMap { String(self[$0]) }
- }
- }
- }
- "hi hello".capturedGroups(regex: "(\\w*)\\s(\\w*)".regex) // ["hi", "hello"]
- "hi hello".matches(regex: "(\\w*)\\s(\\w*)".regex) // ["hi hello", "hi", "hello"]
Add Comment
Please, Sign In to add comment