Tokenize Expressions With text/scanner

Split a small expression language into identifiers, numbers, and operators with text/scanner, printing each token with its position.

GoCli Tooling

Code

gosnippet
32 lines
package main

import (
	"fmt"
	"strings"
	"text/scanner"
)

func main() {
	const src = "total = price * 1.08 + shipping\n"

	var s scanner.Scanner
	s.Init(strings.NewReader(src))
	s.Mode = scanner.ScanIdents | scanner.ScanFloats | scanner.ScanChars
	s.Whitespace = 1<<'\t' | 1<<'\n' | 1<<'\r' | 1<<' '

	// 逐个 token 读取,TokenText 返回原始字面量
	for tok := s.Scan(); tok != scanner.EOF; tok = s.Scan() {
		text := s.TokenText()
		pos := s.Position
		fmt.Printf("%-10s line=%d col=%d\n", text, pos.Line, pos.Column)
	}

	// Error 回调可捕获字母表之外的字符
	var bad scanner.Scanner
	bad.Init(strings.NewReader("a $ b"))
	bad.Error = func(_ *scanner.Scanner, msg string) {
		fmt.Println("scanner error:", msg)
	}
	for bad.Scan() != scanner.EOF {
	}
}

The code as it executes

Tokenize Expressions With text/scanner is built around the function main.

Iteration happens inside for tok := s.Scan(); tok != scanner.EOF; tok = s.Scan() — everything outside it runs once.

Putting it to use

The demo output is labeled (scanner error:), so every line in the printed output names the step that produced it.

Core lines

s.Mode = scanner.ScanIdents | scanner.ScanFloats | scanner.ScanChars

Interactive Tools for This Topic

FAQ

What does Tokenize Expressions With text/scanner print when run?
Invoke the file as-is — the `scanner error:` prefixes identify which step printed each line.