From cd2b800b04a81fc0bbe841ef6d96588a0603601c Mon Sep 17 00:00:00 2001 From: Aadhavan Srinivasan Date: Sat, 26 Oct 2024 13:21:00 -0400 Subject: [PATCH] Fixed greediness of kleene star --- matching.go | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/matching.go b/matching.go index 07a7eff..8f2f855 100644 --- a/matching.go +++ b/matching.go @@ -29,8 +29,11 @@ func findAllMatches(start *State, str string) (indices []matchIndex) { return findAllMatchesHelper(start, str, make([]matchIndex, 0), 0) } func findAllMatchesHelper(start *State, str string, indices []matchIndex, offset int) []matchIndex { - // 'Base case' - exit if string is empty + // 'Base case' - exit if string is empty. If the starting state is a last-state, then append the final set of indices (trailing whitespace) if len(str) == 0 { + if start.isLast { + indices = append(indices, matchIndex{offset, offset + 1}) + } return indices } @@ -74,16 +77,17 @@ func findAllMatchesHelper(start *State, str string, indices []matchIndex, offset if len(state.transitions[int(str[i])]) > 0 { tempStates = append(tempStates, state.transitions[int(str[i])]...) foundPath = true - } else { - // This enables the 'greedy' behavior - last-state status is only checked if we can't match anything else + } + } + + if foundPath == false { + // This enables the 'greedy' behavior - last-state status is only checked if we didn't find a path forward + for _, state := range currentStates { if state.isLast { endIdx = i indices = append(indices, matchIndex{startIdx + offset, endIdx + offset}) } } - } - - if foundPath == false { // Recursion - match with rest of string if we have nowhere to go. If we haven't moved in the string, increment the counter by 1 to ensure we don't keep trying the same string over and over if i == startingFrom { i++