Wrote function to find the 'n'th match of a regex

master
Aadhavan Srinivasan 2 weeks ago
parent 3fa4d0f75e
commit 4373d35216

@ -138,6 +138,27 @@ func pruneIndices(indices []Match) []Match {
return toRet return toRet
} }
// findNthMatch finds the 'n'th match of the regex represented by the given start-state, with
// the given string.
// It returns an error (!= nil) if there are fewer than 'n' matches in the string.
func findNthMatch(start *State, str []rune, numGroups int, n int) (Match, error) {
idx := 0
matchNum := 0
var matchFound bool
var matchIdx Match
for idx <= len(str) {
matchFound, matchIdx, idx = findAllMatchesHelper(start, str, idx, numGroups)
if matchFound {
matchNum++
}
if matchNum == n {
return matchIdx, nil
}
}
// We haven't found the nth match after scanning the string - Return an error
return nil, fmt.Errorf("Invalid match index. Too few matches found.")
}
// findAllMatches tries to find all matches of the regex represented by given start-state, with // findAllMatches tries to find all matches of the regex represented by given start-state, with
// the given string // the given string
func findAllMatches(start *State, str []rune, numGroups int) []Match { func findAllMatches(start *State, str []rune, numGroups int) []Match {

Loading…
Cancel
Save