Tokenize Expressions With text/scanner
Split a small expression language into identifiers, numbers, and operators with text/scanner, printing each token with its position.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.