Regex Named Capture Groups Parse Log Lines

Named capture groups with ?P<name> pull structured fields out of log lines, and SubexpNames builds a name-to-value map without positional guessing.

GoCli Tooling

Code

snippet
package main

import (
	"fmt"
	"regexp"
	"strconv"
)

// Named groups (?P<name>...) give each submatch a name instead of guessing by index
var line = regexp.MustCompile(`^(?P<level>INFO|WARN|ERROR) (?P<service>[\w-]+) took (?P<ms>\d+)ms$`)

func main() {
	entry := "WARN billing-api took 137ms"
	m := line.FindStringSubmatch(entry)
	if m == nil {
		panic("unmatched line")
	}

	// SubexpNames returns each group's name: entry 0 is the whole match and is unnamed
	fields := make(map[string]string)
	for i, name := range line.SubexpNames() {
		if i > 0 {
			fields[name] = m[i]
		}
	}
	fmt.Println(fields["level"], fields["service"])

	// Numeric fields go through strconv to become ints
	ms, err := strconv.Atoi(fields["ms"])
	if err != nil {
		panic(err)
	}
	fmt.Println("slow:", ms > 100)

	// Non-matching lines return nil and fall into the alert branch
	fmt.Println("unmatched:", line.FindStringSubmatch("garbage line") == nil)
}

How it works

Count the function main as the entire surface area of Regex Named Capture Groups Parse Log Lines.

Repetition is confined to for i, name := range line.SubexpNames() — the rest of the file is straight-line. Nothing continues past an unchecked error — 1 if err != nil branch, each ending in panic(err).

What to watch for

  • Adapting this to library code usually means replacing the panic(err) calls with error returns the caller can branch on.

Using it

Look for the slow:, unmatched: prefixes when the file runs; they tie each line to its step.

Key statements

for i, name := range line.SubexpNames() {
	if i > 0 {
		fields[name] = m[i]
	}
}
if err != nil {
	panic(err)
}
fields := make(map[string]string)

Interactive Tools for This Topic

FAQ

How should callers handle failures?
By terminating the run: `panic(err)` fires at each of the 1 check, so callers see failures only as a stopped program.
What does Regex Named Capture Groups Parse Log Lines print when run?
Execute the whole file; each printed line is prefixed with a label like `slow:`, `unmatched:`.