One simple example in the Flex manual is a scanner that counts characters and lines. The program is similar in Nex:

/

/{ nLines++; nChars++ } /./{ nChars++ } // package main import ("fmt";"os") func main() { var nLines, nChars int NN_FUN(NewLexer(os.Stdin)) fmt.Printf("%d %d

", nLines, nChars) }

The syntax resembles Awk more than Flex: each regex must be delimited. An empty regex terminates the rules section and signifies the presence of user code, which is printed on standard output with NN_FUN replaced by the generated scanner.

Name the above example lc.nex. Then compile and run it by typing:

$ nex -r -s lc.nex

The program runs on standard input and output. For example:

$ nex -r -s lc.nex < /usr/share/dict/words 99171 938587

To generate Go code for a scanner without compiling and running it, type:

$ nex -s < lc.nex # Prints code on standard output.

or:

$ nex -s lc.nex # Writes code to lc.nn.go

The NN_FUN macro is primitive, but I was unable to think of another way to achieve an Awk-esque feel. Purists unable to tolerate text substitution will need more code:

/

/{ lval.l++; lval.c++ } /./{ lval.c++ } // package main import ("fmt";"os") type yySymType struct { l, c int } func main() { v := new(yySymType) NewLexer(os.Stdin).Lex(v) fmt.Printf("%d %d

", v.l, v.c) }

and must run nex without the -s option:

$ nex lc.nex