Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Existing survey of text parsers / lexers in Go.

Lexer / Parser in Go

In Go, one of the cleanest examples of parsing text is the lexer design used in text/template. You can find the current source here.

You can find the explination here:

Video: Lexical Scanning in Go - Rob Pike


This designed has been used by many others as a simple way to reason about state without writing a complex state machine.

In the years since it was first written (and the talk was given), the only major changes (besides small bug fixes and features) is the additional tracking of which line we are on, and the concept of starting/ending delimiters.

Existing Work has a nice walkthrough of what is going on. While lacking unit tests, it seems to be the best API for a re-usable lexer.

Illustrated guide to how the cursors move:

Simple example of a lexer that just reverses words:

Simple lexer expecting you to provide stateFn to run:

Lexer designed for io.Reader stream and parsing of text tokens for NLP: Furthermore, this lexer also keeps track of the line number and column of the found tokens. Originally used when scaning source code. Handles complex runs like URL's.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.