Regex end modifier not returning results in a Go program -
i have simple program in go aid in learning regular expressions. runs in infinite loop , has 2 channels, 1 used provide input (input contains regex pattern , subject), , second one, provides output.
usage: main.exe (cat)+ catcatdog
however there propably wrong in code, can't seem results $
modifier.
for example, expect "cat" output from
main.exe cat$ cat\ndog
yet receive 0 results.
code:
package main import ( "fmt" "regexp" "bufio" "os" "strings" ) type regexrequest struct { regex string subject string } func main() { regexrequests := make(chan *regexrequest) defer close(regexrequests) regexanswers, err := createresolver(regexrequests) defer close(regexanswers) if(err != nil) { // todo: panics when exited via ctrl+c panic(err) } interact(regexrequests, regexanswers) } func interact(regexrequests chan *regexrequest, regexanswers chan []string) { { fmt.println("enter regex , subject: ") reader := bufio.newreader(os.stdin) line, err := reader.readstring('\n') if(err != nil) { panic(err) } regandstring := strings.splitn(line, " ", 2); if len(regandstring) != 2 { fmt.println("invalid input, expected [regex][space][subject]") continue } regexrequests <- ®exrequest{ regandstring[0], regandstring[1] } result := <- regexanswers var filteredresult []string _, element := range result { if(element != "") { filteredresult = append(filteredresult, element) } else { filteredresult = append(filteredresult, "empty"); } } fmt.println(strings.join(filteredresult, " ")) } } func createresolver(inputchan chan *regexrequest)(outputchan chan []string, err error) { if(cap(inputchan) > 0) { return nil, fmt.errorf("expected unbuffered channel") } outputchan = make(chan []string) err = nil go func() { { var regreq *regexrequest= (<- inputchan); var regex *regexp.regexp = regexp.mustcompile(regreq.regex) outputchan <- regex.findallstring(regreq.subject, -1) } }() return }
check regex
pattern. example,
enter regex , subject: cat$ cat\ndog enter regex , subject: ^cat cat\ndog cat
Comments
Post a Comment