Python Practice › RegEx Programs › Program 13

Parse log lines with named groups

EasyRegEx Programs · 13 of 20

Write a Python program to parse “LEVEL date message” log lines into dictionaries.

Advertisement
Output
{'level': 'ERROR', 'date': '2026-11-02', 'msg': 'db timeout'}
{'level': 'INFO', 'date': '2026-11-02', 'msg': 'started'}

Approach

  1. Named groups and groupdict().

Solution

Python
import re LINE = re.compile(r"(?P<level>[A-Z]+) (?P<date>\d{4}-\d{2}-\d{2}) (?P<msg>.+)")for line in ["ERROR 2026-11-02 db timeout", "INFO 2026-11-02 started"]:    print(LINE.match(line).groupdict())
Output
{'level': 'ERROR', 'date': '2026-11-02', 'msg': 'db timeout'}
{'level': 'INFO', 'date': '2026-11-02', 'msg': 'started'}

Learn the concept

New to this topic? Read the lesson, then come back.

More regex programs

← All 20 RegEx Programs

Leave a Comment