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)
// 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') {
matchIndices := findAllMatches(startState, test_str) matchIndices := findAllMatches(startState, test_str)
// 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
inColor := false // This should make checking O(1) instead of O(n)
indicesToPrint := new_uniq_arr[int]()
for _, idx := range matchIndices {
indicesToPrint.add(genRange(idx.startIdx, idx.endIdx)...)
}
if len(matchIndices) > 0 { if len(matchIndices) > 0 {
for i, c := range test_str { for i, c := range test_str {
for _, indices := range matchIndices { if indicesToPrint.contains(i) {
if i >= indices.startIdx && i < indices.endIdx { color.New(color.FgRed).Fprintf(out, "%c", c)
color.New(color.FgRed).Printf("%c", c) } else {
inColor = true fmt.Fprintf(out, "%c", c)
break
} }
} }
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