ZetCode

Golang fmt.Sscanf function

last modified May 8, 2025

This tutorial explains how to use the fmt.Sscanf function in Go. We'll cover string parsing basics with practical examples of formatted input.

The fmt.Sscanf function scans a string according to a format specifier. It stores successive space-separated values into arguments. This is useful for parsing structured text data into variables.

In Go, fmt.Sscanf provides formatted scanning from strings similar to C's sscanf. It returns the number of items successfully parsed. The function is part of Go's fmt package.

Basic Sscanf usage

The simplest use of fmt.Sscanf parses basic values from a string. This example demonstrates parsing integers and strings.
Note: The format string must match the input string structure.

basic_sscanf.go
package main

import (
    "fmt"
)

func main() {
    input := "John 25 5.9"
    var name string
    var age int
    var height float64
    
    n, err := fmt.Sscanf(input, "%s %d %f", &name, &age, &height)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    
    fmt.Printf("Parsed %d values: %s is %d years old and %.1f feet tall\n",
        n, name, age, height)
}

The function scans the input string into three variables. The return value shows how many items were successfully parsed. Error handling is important.

Parsing date components

fmt.Sscanf can extract structured data like date components. This example shows parsing a date string into its constituent parts.

date_parsing.go
package main

import (
    "fmt"
)

func main() {
    dateStr := "2025-05-15"
    var year, month, day int
    
    n, err := fmt.Sscanf(dateStr, "%d-%d-%d", &year, &month, &day)
    if err != nil || n != 3 {
        fmt.Println("Failed to parse date")
        return
    }
    
    fmt.Printf("Parsed date: Year=%d, Month=%d, Day=%d\n",
        year, month, day)
}

The format string matches the date structure exactly. We check both the error and number of parsed items for complete validation.

Handling different input formats

fmt.Sscanf can handle various input formats flexibly. This example demonstrates parsing the same data in different formats.

multiple_formats.go
package main

import (
    "fmt"
)

func main() {
    inputs := []string{
        "Temperature: 25.5C",
        "Humidity: 60%",
        "Pressure: 1013hPa",
    }
    
    for _, input := range inputs {
        var value float64
        var unit string
        
        _, err := fmt.Sscanf(input, "%f%s", &value, &unit)
        if err != nil {
            fmt.Printf("Failed to parse '%s'\n", input)
            continue
        }
        
        fmt.Printf("Value: %.1f, Unit: %s\n", value, unit)
    }
}

The function skips non-numeric prefixes automatically. This makes it useful for parsing semi-structured data with varying formats.

Parsing with verb modifiers

Format verbs can include width specifiers and other modifiers. This example shows advanced parsing with verb modifiers.

verb_modifiers.go
package main

import (
    "fmt"
)

func main() {
    logEntry := "[ERROR] 2025/05/15 14:30:22 Connection timeout"
    var level, date, time, message string
    
    n, err := fmt.Sscanf(logEntry, "[%7s] %10s %8s %[^\n]",
        &level, &date, &time, &message)
    if err != nil || n != 4 {
        fmt.Println("Failed to parse log entry")
        return
    }
    
    fmt.Printf("Level: %s\nDate: %s\nTime: %s\nMessage: %s\n",
        level, date, time, message)
}

Width specifiers (%7s) and scan sets (%[^\n]) provide precise control over parsing. This is useful for structured logs.

Parsing hexadecimal and binary values

fmt.Sscanf supports parsing numbers in different bases. This example demonstrates hexadecimal and binary number parsing.

number_bases.go
package main

import (
    "fmt"
)

func main() {
    colorStr := "Hex: #FF00FF, Binary: 101010"
    var r, g, b int
    var binary int
    
    n, err := fmt.Sscanf(colorStr, "Hex: #%2x%2x%2x, Binary: %b",
        &r, &g, &b, &binary)
    if err != nil || n != 4 {
        fmt.Println("Failed to parse values")
        return
    }
    
    fmt.Printf("Color: R=%d, G=%d, B=%d\nBinary: %d\n",
        r, g, b, binary)
}

The %x verb parses hexadecimal values, while %b parses binary. Format verbs match those used in fmt.Printf.

Ignoring parts of input

You can skip parts of the input using the * modifier. This example shows how to ignore unwanted portions of text.

ignoring_parts.go
package main

import (
    "fmt"
)

func main() {
    data := "Name: John, Age: 25, City: New York"
    var name string
    var age int
    
    n, err := fmt.Sscanf(data, "Name: %s, Age: %d, City: %*s",
        &name, &age)
    if err != nil || n != 2 {
        fmt.Println("Failed to parse data")
        return
    }
    
    fmt.Printf("Name: %s, Age: %d\n", name, age)
}

The %*s verb scans but doesn't store the city value. This technique is useful when you need to skip irrelevant data.

Parsing complex structures

fmt.Sscanf can parse nested structures with careful formatting. This example demonstrates parsing a complex configuration string.

complex_parsing.go
package main

import (
    "fmt"
)

func main() {
    config := "Server{IP:192.168.1.1, Port:8080, Active:true}"
    var ip1, ip2, ip3, ip4 int
    var port int
    var active bool
    
    n, err := fmt.Sscanf(config,
        "Server{IP:%d.%d.%d.%d, Port:%d, Active:%t}",
        &ip1, &ip2, &ip3, &ip4, &port, &active)
    if err != nil || n != 6 {
        fmt.Println("Failed to parse config")
        return
    }
    
    fmt.Printf("Server: %d.%d.%d.%d:%d, Active: %t\n",
        ip1, ip2, ip3, ip4, port, active)
}

The format string matches the structure exactly. Each component is parsed into separate variables. This approach works for many text formats.

Source

Go fmt package documentation

This tutorial covered the fmt.Sscanf function in Go with practical examples of string parsing and formatted input scanning.

Author

My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.

List all Golang tutorials.