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 (
"bufio"
"flag"
"fmt"
"io"
"os"
@ -370,18 +371,22 @@ func thompson(re []postfixNode) *State {
}
func main() {
invertFlag := flag.Bool("v", false, "Invert match.")
//onlyFlag := flag.Bool("o", false, "Print only colored content.")
flag.Parse()
// Process:
// 1. Convert regex into postfix notation (Shunting-Yard algorithm)
// a. Add explicit concatenation operators to facilitate this
// 2. Build NFA from postfix representation (Thompson's algorithm)
// 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")
os.Exit(22)
}
var re string
re = os.Args[1]
re = flag.Args()[0]
var test_str string
var err error
// Create reader for stdin and writer for stdout
@ -399,16 +404,24 @@ func main() {
for _, idx := range matchIndices {
indicesToPrint.add(genRange(idx.startIdx, idx.endIdx)...)
}
if len(matchIndices) > 0 {
for i, c := range test_str {
if indicesToPrint.contains(i) {
color.New(color.FgRed).Fprintf(out, "%c", c)
} else {
fmt.Fprintf(out, "%c", c)
}
// If we are inverting, then we should print the indices which _didn't_ match
// in color.
if *invertFlag {
oldIndices := indicesToPrint.values()
indicesToPrint = new_uniq_arr[int]()
// 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()
if err != nil {

Loading…
Cancel
Save