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.
Code
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
Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.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.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.