Editor

Parse a Log Entry

Intermediate · Write the code · from Python Regular Expressions: Pattern Matching from Basics to Advanced

From the lesson: Python Regular Expressions: Pattern Matching from Basics to Advanced

Imagine you're working at a help desk and need to find every email address buried in thousands of support tickets. You could scan each line character by character, but that would take forever. Regular expressions let you describe the pattern of an email address, and Python finds every match for you.

Read the lesson

Write a function parse_log(entry) that extracts the timestamp, level, and message from a log entry formatted as "[HH:MM:SS] LEVEL: message". Return a dictionary with keys "time", "level", and "message". Use named groups. If the entry doesn't match, return None.

import re
def parse_log(entry):
# Use named groups: (?P<name>pattern)
pass
result = parse_log('[14:23:05] ERROR: disk full')
if result:
print(result['time'])
print(result['level'])
print(result['message'])

More Regex exercises

All Python exercises · 50 practice problems · Standard Library Essentials quiz