diff --git a/main.go b/main.go index 5e7b0da..d5ce1b2 100644 --- a/main.go +++ b/main.go @@ -697,11 +697,14 @@ func main() { } } test_runes = []rune(test_str) - matchIndices := findAllMatches(startState, test_runes, numGroups) - - // If we are trying to print an invalid index, we just assume no specific matches will be printed. - if matchNumFlagEnabled && *matchNum > len(matchIndices) { - matchNumFlagEnabled = false + matchIndices := make([]Match, 0) + if matchNumFlagEnabled { + tmp, err := findNthMatch(startState, test_runes, numGroups, *matchNum) + if err == nil { + matchIndices = append(matchIndices, tmp) + } + } else { + matchIndices = findAllMatches(startState, test_runes, numGroups) } if *printMatchesFlag { @@ -711,14 +714,8 @@ func main() { if !(*multiLineFlag) { fmt.Fprintf(out, "Line %d:\n", lineNum) } - for i, m := range matchIndices { - // Only print a match if: - // a. We are _not_ printing just one match - // OR - // b. We _are_ printing just one match, and this is that match - if !matchNumFlagEnabled || (i+1) == *matchNum { // Match indexes start from 1; loop counter starts from 0 - fmt.Fprintf(out, "%s\n", m.toString()) - } + for _, m := range matchIndices { + fmt.Fprintf(out, "%s\n", m.toString()) } err := out.Flush() if err != nil { @@ -765,14 +762,12 @@ func main() { if substituteFlagEnabled { for i := range test_runes { inMatchIndex := false - for idx, m := range matchIndices { - if !matchNumFlagEnabled || (idx+1) == *matchNum { - if i == m[0].startIdx { - fmt.Fprintf(out, "%s", *substituteText) - i = m[0].endIdx - inMatchIndex = true - break - } + for _, m := range matchIndices { + if i == m[0].startIdx { + fmt.Fprintf(out, "%s", *substituteText) + i = m[0].endIdx + inMatchIndex = true + break } } if !inMatchIndex { @@ -781,13 +776,7 @@ func main() { } } else { for i, c := range test_runes { - // Explanation: - // We print a letter in red if: - // 1. It is in the 'indicesToPrint' - // 2. One of the following: - // a. The '-m' flag is disabled - // b. The '-m' flag is enabled, and our current index is in the bounds of the specific match - if indicesToPrint.contains(i) && (!matchNumFlagEnabled || (i >= matchIndices[*matchNum-1][0].startIdx && i < matchIndices[*matchNum-1][0].endIdx)) { + if indicesToPrint.contains(i) { color.New(color.FgRed).Fprintf(out, "%c", c) // Newline after every match - only if -o is enabled and -v is disabled. if *onlyFlag && !(*invertFlag) {