Skip to content

Commit

Permalink
Merge pull request #41 from Fueled/feat/regex-groups
Browse files Browse the repository at this point in the history
[Regex] Match and return regex captured groups
  • Loading branch information
stephanecopin authored Sep 2, 2020
2 parents 2ced1b2 + f9f1bf3 commit 03afd1f
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions FueledUtils/Core/Regex.swift
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,25 @@ public struct Regex {
public func match(_ string: String, options: NSRegularExpression.MatchingOptions = []) -> Bool {
return implementation.numberOfMatches(in: string, options: options, range: string.nsRange) != 0
}

/// Match all the captured groups if any.
///
/// - Parameters:
/// - pattern: The string to match the regex against.
/// - options: The options to use when matching the regular expression
/// against the given string.
/// - Returns: The captured groups.
///
/// - Note: By default, NSRegularExpression exposes the matching text (not the
/// group) as the first (index 0) element of the NSTextCheckingResult. This
/// is ignored in the returned value, as it is not a captured group.
public func groups(in string: String, options: NSRegularExpression.MatchingOptions = []) -> [[String]] {
let matches = implementation.matches(in: string, options: options, range: string.nsRange)
return matches
.map { match in (1..<match.numberOfRanges).map { match.range(at: $0) } }
.map { $0.compactMap { Range($0, in: string) } }
.map { $0.map { String(string[$0]) } }
}
}

///
Expand Down

0 comments on commit 03afd1f

Please sign in to comment.