Last active
October 22, 2018 06:20
-
-
Save TerryCK/203aec155116db9b8d296243daef1ed0 to your computer and use it in GitHub Desktop.
Regular expression captureGroups
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 | |
struct Regex { | |
let pattern: String | |
} | |
protocol RegexMatchable : StringProtocol { | |
var regex: Regex { get } | |
func matches(regex: Regex, options: NSRegularExpression.Options) -> [String] | |
func capturedGroups(regex: Regex, options: NSRegularExpression.Options) -> [String] | |
} | |
extension Matchable { | |
var regex: Regex { return Regex(pattern: String(self)) } | |
} | |
extension String : RegexMatchable { | |
public func capturedGroups(with regex: Regex, options: NSRegularExpression.Options = []) -> [String] { | |
let m = matches(with: regex, options: options) | |
return m.count>1 ? Array(m.dropFirst()) : [] | |
} | |
public func matches(with 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).compactMap { | |
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"] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment