From 6f9173f7714e22711aed2053b19290039992f416 Mon Sep 17 00:00:00 2001 From: Aadhavan Srinivasan Date: Fri, 3 Jan 2025 19:17:24 -0500 Subject: [PATCH] Finished support for -m flag; refactoring pending --- main.go | 28 +++++++++++++++++++++------- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/main.go b/main.go index 7742649..5e7b0da 100644 --- a/main.go +++ b/main.go @@ -698,6 +698,12 @@ 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 + } + if *printMatchesFlag { // if we are in single line mode, print the line on which // the matches occur @@ -759,12 +765,14 @@ func main() { if substituteFlagEnabled { for i := range test_runes { inMatchIndex := false - for _, idx := range matchIndices { - if i == idx[0].startIdx { - fmt.Fprintf(out, "%s", *substituteText) - i = idx[0].endIdx - inMatchIndex = true - break + 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 + } } } if !inMatchIndex { @@ -773,7 +781,13 @@ func main() { } } else { for i, c := range test_runes { - if indicesToPrint.contains(i) { + // 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)) { color.New(color.FgRed).Fprintf(out, "%c", c) // Newline after every match - only if -o is enabled and -v is disabled. if *onlyFlag && !(*invertFlag) {