SScanf Parses Fixed Format Strings

Extract typed fields from fixed-layout strings with fmt.Sscanf, where verbs, literals, and skipped tokens in the format string mirror the input exactly.

GoData Integrity

Code

gosnippet
31 lines
package main

import (
	"fmt"
)

func main() {
	// Sscanf 按格式串逐项解析:动词对应变量,字面量必须原样匹配。
	// 陷阱:%s 只在空白处停止——URL 风格输入 "postgres://db:5432" 配
	// "%s:%d" 时,%s 会把 "db:5432" 整个吞掉,随后 %d 无输入可读,
	// 返回 n=1、err=unexpected EOF;无空格字段先用 strings.Split 切开
	var host string
	var port int
	n, err := fmt.Sscanf("db.example.com 5432", "%s %d", &host, &port)
	fmt.Println("fields:", n, "err:", err, "host:", host, "port:", port)

	// %d 跳过不想要的字段:只留月份和年份
	var month, year int
	fmt.Sscanf("2026-11-20", "%*d-%d-%d", &month, &year)
	fmt.Println("month:", month, "year:", year)

	// 字面量不匹配时解析提前失败:n 反映已成功赋值的字段数
	var q int
	n2, err2 := fmt.Sscanf("weight=42kg", "weight=%d lb", &q)
	fmt.Println("fields:", n2, "err:", err2)

	// 空格在格式串里匹配任意空白:分隔符宽窄都能吃下
	var a, b int
	fmt.Sscanf("3    7", "%d %d", &a, &b)
	fmt.Println("pair:", a, b)
}

What the code does

The working parts are the function main.

Points of care

  • Nothing to install: every API here comes with the runtime itself.

Applying it

The main signature is written as func main()

The run prints labeled output — fields:, month:, pair: — when the file runs.

Statements that decide the outcome

n, err := fmt.Sscanf("db.example.com 5432", "%s %d", &host, &port)

Interactive Tools for This Topic

FAQ

What does SScanf Parses Fixed Format Strings print when run?
Run it as a complete program — the output lines carry labels such as `fields:`, `month:`, `pair:`.