Added support for -v flag, to invert which values are printed in color. Also got rid of unecessary 'else' clause

master
Aadhavan Srinivasan 1 month ago
parent 11641596fa
commit f2b8812b05

@ -2,6 +2,7 @@ package main
import ( import (
"bufio" "bufio"
"flag"
"fmt" "fmt"
"io" "io"
"os" "os"
@ -370,18 +371,22 @@ func thompson(re []postfixNode) *State {
} }
func main() { func main() {
invertFlag := flag.Bool("v", false, "Invert match.")
//onlyFlag := flag.Bool("o", false, "Print only colored content.")
flag.Parse()
// Process: // Process:
// 1. Convert regex into postfix notation (Shunting-Yard algorithm) // 1. Convert regex into postfix notation (Shunting-Yard algorithm)
// a. Add explicit concatenation operators to facilitate this // a. Add explicit concatenation operators to facilitate this
// 2. Build NFA from postfix representation (Thompson's algorithm) // 2. Build NFA from postfix representation (Thompson's algorithm)
// 3. Run the string against the NFA // 3. Run the string against the NFA
if len(os.Args) != 2 { if len(flag.Args()) != 1 { // flag.Args() also strips out program name
fmt.Println("ERROR: Missing cmdline args") fmt.Println("ERROR: Missing cmdline args")
os.Exit(22) os.Exit(22)
} }
var re string var re string
re = os.Args[1] re = flag.Args()[0]
var test_str string var test_str string
var err error var err error
// Create reader for stdin and writer for stdout // Create reader for stdin and writer for stdout
@ -399,16 +404,24 @@ func main() {
for _, idx := range matchIndices { for _, idx := range matchIndices {
indicesToPrint.add(genRange(idx.startIdx, idx.endIdx)...) indicesToPrint.add(genRange(idx.startIdx, idx.endIdx)...)
} }
if len(matchIndices) > 0 { // If we are inverting, then we should print the indices which _didn't_ match
for i, c := range test_str { // in color.
if indicesToPrint.contains(i) { if *invertFlag {
color.New(color.FgRed).Fprintf(out, "%c", c) oldIndices := indicesToPrint.values()
} else { indicesToPrint = new_uniq_arr[int]()
fmt.Fprintf(out, "%c", c) // Explanation:
} // Find all numbers from 0 to len(test_str) that are NOT in oldIndices.
// These are the values we want to print, now that we have inverted the match.
// Re-initialize indicesToPrint and add all of these values to it.
indicesToPrint.add(setDifference(genRange(0, len(test_str)), oldIndices)...)
}
for i, c := range test_str {
if indicesToPrint.contains(i) {
color.New(color.FgRed).Fprintf(out, "%c", c)
} else {
fmt.Fprintf(out, "%c", c)
} }
} else {
fmt.Fprint(out, test_str)
} }
err = out.Flush() err = out.Flush()
if err != nil { if err != nil {

Loading…
Cancel
Save