Python's re module supports advanced pattern matching capabilities including named capture groups, lookaheads, lookbehinds, and pattern flags.
(?P<name>pattern): Named capture group accessible via match.group('name').(?=pattern): Positive lookahead assertion.(?<=pattern): Positive lookbehind assertion.re.IGNORECASE / re.MULTILINE / re.VERBOSE: Modifiers for regex engine execution.import re
from typing import Dict, Optional
def parse_log_line(log_line: str) -> Optional[Dict[str, str]]:
"""Extract structured metadata from log string using named capture groups."""
pattern = re.compile(
r'\[(?P<timestamp>[^\]]+)\]\s+'
r'(?P<level>INFO|WARN|ERROR)\s+'
r'(?P<component>\w+):\s+'
r'(?P<message>.*)',
re.VERBOSE
)
match = pattern.search(log_line)
if match:
return match.groupdict()
return None
if __name__ == "__main__":
sample_log = "[2026-08-15 14:20:00] ERROR DatabaseService: Connection timeout after 3000ms"
parsed = parse_log_line(sample_log)
print("Parsed Log Metadata:", parsed)
re.VERBOSE for Complex Patterns: re.VERBOSE allows adding whitespace and comments inside multi-line regex patterns for readability.(?P<name>...) instead of positional groups (1) for self-documenting code.match() vs search(): re.match() checks only at the start of the string; re.search() scans the entire string.Write a regex with named capture groups (?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2}) to parse ISO dates.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With