Rewrote behavior of '-m' flag to use the 'nth match' function from matching.go

master
Aadhavan Srinivasan 2 weeks ago
parent 4373d35216
commit 72263509d3

@ -697,11 +697,14 @@ func main() {
} }
} }
test_runes = []rune(test_str) test_runes = []rune(test_str)
matchIndices := findAllMatches(startState, test_runes, numGroups) matchIndices := make([]Match, 0)
if matchNumFlagEnabled {
// If we are trying to print an invalid index, we just assume no specific matches will be printed. tmp, err := findNthMatch(startState, test_runes, numGroups, *matchNum)
if matchNumFlagEnabled && *matchNum > len(matchIndices) { if err == nil {
matchNumFlagEnabled = false matchIndices = append(matchIndices, tmp)
}
} else {
matchIndices = findAllMatches(startState, test_runes, numGroups)
} }
if *printMatchesFlag { if *printMatchesFlag {
@ -711,15 +714,9 @@ func main() {
if !(*multiLineFlag) { if !(*multiLineFlag) {
fmt.Fprintf(out, "Line %d:\n", lineNum) fmt.Fprintf(out, "Line %d:\n", lineNum)
} }
for i, m := range matchIndices { for _, 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()) fmt.Fprintf(out, "%s\n", m.toString())
} }
}
err := out.Flush() err := out.Flush()
if err != nil { if err != nil {
panic(err) panic(err)
@ -765,8 +762,7 @@ func main() {
if substituteFlagEnabled { if substituteFlagEnabled {
for i := range test_runes { for i := range test_runes {
inMatchIndex := false inMatchIndex := false
for idx, m := range matchIndices { for _, m := range matchIndices {
if !matchNumFlagEnabled || (idx+1) == *matchNum {
if i == m[0].startIdx { if i == m[0].startIdx {
fmt.Fprintf(out, "%s", *substituteText) fmt.Fprintf(out, "%s", *substituteText)
i = m[0].endIdx i = m[0].endIdx
@ -774,20 +770,13 @@ func main() {
break break
} }
} }
}
if !inMatchIndex { if !inMatchIndex {
fmt.Fprintf(out, "%c", test_runes[i]) fmt.Fprintf(out, "%c", test_runes[i])
} }
} }
} else { } else {
for i, c := range test_runes { for i, c := range test_runes {
// Explanation: if indicesToPrint.contains(i) {
// 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) color.New(color.FgRed).Fprintf(out, "%c", c)
// Newline after every match - only if -o is enabled and -v is disabled. // Newline after every match - only if -o is enabled and -v is disabled.
if *onlyFlag && !(*invertFlag) { if *onlyFlag && !(*invertFlag) {

Loading…
Cancel
Save