Read multiple lines from stdin and apply regex to each one; Convert the array of matchIndex structs into a flat array of indices; speeds up process of checking if we have to print a character in color

master
Aadhavan Srinivasan 1 month ago
parent b55b80ec6c
commit 11641596fa

@ -383,33 +383,39 @@ func main() {
var re string var re string
re = os.Args[1] re = os.Args[1]
var test_str string var test_str string
// Read test string from stdin var err error
// Create reader for stdin and writer for stdout
reader := bufio.NewReader(os.Stdin) reader := bufio.NewReader(os.Stdin)
test_str, err := reader.ReadString('\n') out := bufio.NewWriter(os.Stdout)
if err != nil && err != io.EOF {
panic(err)
}
//fmt.Scanln(&test_str)
re_postfix := shuntingYard(re) re_postfix := shuntingYard(re)
startState := thompson(re_postfix) startState := thompson(re_postfix)
matchIndices := findAllMatches(startState, test_str) // Read every string from stdin until we encounter an error. If the error isn't EOF, panic.'
for test_str, err = reader.ReadString('\n'); err == nil; test_str, err = reader.ReadString('\n') {
inColor := false matchIndices := findAllMatches(startState, test_str)
if len(matchIndices) > 0 { // Decompose the array of matchIndex structs into a flat unique array of ints - if matchIndex is {4,7}, flat array will contain 4,5,6
for i, c := range test_str { // This should make checking O(1) instead of O(n)
for _, indices := range matchIndices { indicesToPrint := new_uniq_arr[int]()
if i >= indices.startIdx && i < indices.endIdx { for _, idx := range matchIndices {
color.New(color.FgRed).Printf("%c", c) indicesToPrint.add(genRange(idx.startIdx, idx.endIdx)...)
inColor = true }
break 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 inColor == false { } else {
fmt.Printf("%c", c) fmt.Fprint(out, test_str)
} }
inColor = false err = out.Flush()
if err != nil {
panic(err)
} }
} else { }
fmt.Print(test_str) if err != io.EOF {
panic(err)
} }
} }

Loading…
Cancel
Save