Python (re)

Logfmt Key-Value Pair in PY

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

Try it in the PY tester →

Pattern

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

Python (re) code

pyPython
import re

pattern = re.compile(r"([a-zA-Z_][\\w.]*)=(\"[^\"]*\"|\\S+)")
input_text = "level=info msg=\"user logged in\" user_id=42"
for m in pattern.finditer(input_text):
    print(m.group(0))

Stdlib `re` module — no third-party dependency. Works on Python 3.6+.

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)