Go (RE2)

Logfmt Key-Value Pair in GO

Parse key=value pairs from logfmt-style log lines, supporting both quoted and unquoted values.

Try it in the GO tester →

Pattern

regexGO
([a-zA-Z_][\w.]*)=("[^"]*"|\S+)   (flags: g)

Go (RE2) code

goGo
package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := regexp.MustCompile(`([a-zA-Z_][\w.]*)=("[^"]*"|\S+)`)
	input := `level=info msg="user logged in" user_id=42`
	for _, match := range re.FindAllString(input, -1) {
		fmt.Println(match)
	}
}

Uses `regexp.MustCompile` (panics on bad patterns at startup) and `FindAllString` for all matches.

How the pattern works

([a-zA-Z_][\w.]*) captures the key: starts with a letter or underscore, followed by word chars or dots. = is a literal separator. ("[^"]*"|\S+) captures the value: either a double-quoted string (allowing spaces inside) or an unquoted sequence of non-whitespace characters.

Examples

Input

level=info msg="user logged in" user_id=42

Matches

  • level=info
  • msg="user logged in"
  • user_id=42

Input

ts=2024-01-15T14:30:00Z status=200 latency=12ms

Matches

  • ts=2024-01-15T14:30:00Z
  • status=200
  • latency=12ms

Same pattern, other engines

← Back to Logfmt Key-Value Pair overview (all engines)