TExcelTAD
Home › Regular Expressions › Regex Mini Project

Regex Mini Project

In this project you'll build a log-file parser step by step. Real systems produce thousands of lines like the ones below every minute, and regular expressions are the classic tool for turning them into structured data you can count, filter and report on.

Here is our sample log:

2025-07-31 08:15:02 INFO  [auth] User lan logged in from 10.0.0.12
2025-07-31 08:15:09 WARN  [db] Slow query took 1532ms
2025-07-31 08:16:40 ERROR [api] GET /orders/42 failed with 500
2025-07-31 08:17:03 INFO  [auth] User bao logged in from 10.0.0.31
2025-07-31 08:18:55 ERROR [db] Connection lost after 3 retries
2025-07-31 08:19:00 DEBUG [cache] hit ratio 0.93

Each line has the same structure: date, time, level (padded to 5 characters), component in brackets, and a free-text message.

Step 1: the timestamp

Start small. Match the date and time at the start of each line, capturing both:

regex · try it yourself
/^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})/gm
2025-07-31 08:15:02 INFO  [auth] User lan logged in from 10.0.0.12
2025-07-31 08:15:09 WARN  [db] Slow query took 1532ms
2025-07-31 08:16:40 ERROR [api] GET /orders/42 failed with 500
3 matches
#1 "2025-07-31 08:15:02" at index 0
   group 1: "2025-07-31"
   group 2: "08:15:02"
#2 "2025-07-31 08:15:09" at index 67
   group 1: "2025-07-31"
   group 2: "08:15:09"
#3 "2025-07-31 08:16:40" at index 121
   group 1: "2025-07-31"
   group 2: "08:16:40"

The m flag is essential: without it ^ would only match at the very beginning of the text.

Step 2: level and component

Add the level — one of a known set of words — then one or more spaces, then the component between brackets:

regex · try it yourself
/^\S+ \S+ (DEBUG|INFO|WARN|ERROR) +\[(\w+)\]/gm
2025-07-31 08:15:02 INFO  [auth] User lan logged in from 10.0.0.12
2025-07-31 08:15:09 WARN  [db] Slow query took 1532ms
2025-07-31 08:16:40 ERROR [api] GET /orders/42 failed with 500
3 matches
#1 "2025-07-31 08:15:02 INFO  [auth]" at index 0
   group 1: "INFO"
   group 2: "auth"
#2 "2025-07-31 08:15:09 WARN  [db]" at index 67
   group 1: "WARN"
   group 2: "db"
#3 "2025-07-31 08:16:40 ERROR [api]" at index 121
   group 1: "ERROR"
   group 2: "api"

+ (a space with +) absorbs the padding after shorter level names. An explicit list of levels is stricter than \w+ — an unexpected level makes the line fail, which is useful for spotting malformed data.

Step 3: the full line with named groups

Now combine everything and capture the message with .* (it's the last field, so greediness is fine). Named groups make the result self-documenting:

regex · try it yourself
/^(?<date>\d{4}-\d{2}-\d{2}) (?<time>\d{2}:\d{2}:\d{2}) (?<level>DEBUG|INFO|WARN|ERROR) +\[(?<comp>\w+)\] (?<msg>.*)$/gm
2025-07-31 08:15:02 INFO  [auth] User lan logged in from 10.0.0.12
2025-07-31 08:16:40 ERROR [api] GET /orders/42 failed with 500
this line is garbage
2 matches
#1 "2025-07-31 08:15:02 INFO  [auth] User lan logged in from 10.0.0.12" at index 0
   group date: "2025-07-31"
   group time: "08:15:02"
   group level: "INFO"
   group comp: "auth"
   group msg: "User lan logged in from 10.0.0.12"
#2 "2025-07-31 08:16:40 ERROR [api] GET /orders/42 failed with 500" at index 67
   group date: "2025-07-31"
   group time: "08:16:40"
   group level: "ERROR"
   group comp: "api"
   group msg: "GET /orders/42 failed with 500"

The garbage line is silently skipped. In a real tool you would count such lines, because a sudden rise usually means the log format changed.

Step 4: pull details out of messages

Messages contain useful values of their own. IPv4 addresses after the word from:

regex · try it yourself
/(?<=from )\d{1,3}(?:\.\d{1,3}){3}\b/g
2025-07-31 08:15:02 INFO  [auth] User lan logged in from 10.0.0.12
2025-07-31 08:17:03 INFO  [auth] User bao logged in from 10.0.0.31
2 matches
#1 "10.0.0.12" at index 57
#2 "10.0.0.31" at index 124

And durations in milliseconds:

regex · try it yourself
/(\d+)ms\b/g
2025-07-31 08:15:09 WARN  [db] Slow query took 1532ms
2025-07-31 08:21:12 WARN  [db] Slow query took 980ms
2 matches
#1 "1532ms" at index 47
   group 1: "1532"
#2 "980ms" at index 101
   group 1: "980"

Step 5: the parser in JavaScript

Put it all together: parse every line into an object, count lines per level, and list the errors.

js · try it yourself
const log = `2025-07-31 08:15:02 INFO  [auth] User lan logged in from 10.0.0.12
2025-07-31 08:15:09 WARN  [db] Slow query took 1532ms
2025-07-31 08:16:40 ERROR [api] GET /orders/42 failed with 500
2025-07-31 08:17:03 INFO  [auth] User bao logged in from 10.0.0.31
2025-07-31 08:18:55 ERROR [db] Connection lost after 3 retries
2025-07-31 08:19:00 DEBUG [cache] hit ratio 0.93
oops, a broken line`;

const LINE = /^(?<date>\d{4}-\d{2}-\d{2}) (?<time>\d{2}:\d{2}:\d{2}) (?<level>DEBUG|INFO|WARN|ERROR) +\[(?<comp>\w+)\] (?<msg>.*)$/gm;

const entries = [...log.matchAll(LINE)].map((m) => ({ ...m.groups }));
const lineCount = log.split("\n").length;

const perLevel = {};
for (const e of entries) perLevel[e.level] = (perLevel[e.level] ?? 0) + 1;

console.log(`parsed ${entries.length} of ${lineCount} lines`);
console.log(perLevel);
for (const e of entries.filter((e) => e.level === "ERROR")) {
  console.log(`${e.time} ${e.comp.padEnd(4)} ${e.msg}`);
}

const users = [...log.matchAll(/User (?<user>\w+) logged in from (?<ip>[\d.]+)/g)]
  .map((m) => `${m.groups.user}@${m.groups.ip}`);
console.log(users);
parsed 6 of 7 lines
{ INFO: 2, WARN: 1, ERROR: 2, DEBUG: 1 }
08:16:40 api  GET /orders/42 failed with 500
08:18:55 db   Connection lost after 3 retries
[ 'lan@10.0.0.12', 'bao@10.0.0.31' ]

Step 6: the same parser in Python

Python's re.VERBOSE lets us spread the line pattern out with comments, and collections.Counter does the counting:

python · try it yourself
import re
from collections import Counter

log = """2025-07-31 08:15:02 INFO  [auth] User lan logged in from 10.0.0.12
2025-07-31 08:15:09 WARN  [db] Slow query took 1532ms
2025-07-31 08:16:40 ERROR [api] GET /orders/42 failed with 500
2025-07-31 08:17:03 INFO  [auth] User bao logged in from 10.0.0.31
2025-07-31 08:18:55 ERROR [db] Connection lost after 3 retries
2025-07-31 08:19:00 DEBUG [cache] hit ratio 0.93"""

LINE = re.compile(r"""
    ^(?P<date>\d{4}-\d{2}-\d{2})\ (?P<time>\d{2}:\d{2}:\d{2})\ +   # timestamp
    (?P<level>DEBUG|INFO|WARN|ERROR)\ +                          # level
    \[(?P<comp>\w+)\]\ (?P<msg>.*)$                               # component, message
""", re.MULTILINE | re.VERBOSE)

entries = [m.groupdict() for m in LINE.finditer(log)]
print(Counter(e["level"] for e in entries))

slow = [int(ms) for ms in re.findall(r"(\d+)ms\b", log)]
print("slow queries:", slow)

by_comp = Counter(e["comp"] for e in entries if e["level"] in ("WARN", "ERROR"))
print("problems by component:", dict(by_comp))
Counter({'INFO': 2, 'ERROR': 2, 'WARN': 1, 'DEBUG': 1})
slow queries: [1532]
problems by component: {'db': 2, 'api': 1}

Notice the escaped spaces \ — in verbose mode ordinary whitespace in the pattern is ignored.

Ideas to extend the project

  • Accept an optional milliseconds part in the time: \d{2}:\d{2}:\d{2}(?:\.\d{3})?.
  • Extract the HTTP method, path and status code from [api] messages with a second pattern.
  • Mask IP addresses for privacy with replace, keeping only the first two octets.
  • Report lines that didn't match the main pattern, with their line numbers.

Test yourself

Why does the line pattern need the m flag?

  1. To ignore case
  2. So ^ and $ match at each line instead of only the whole text
  3. To allow . to match newlines
  4. To find multiple matches

Why list the levels explicitly (DEBUG|INFO|WARN|ERROR) instead of \w+?

  1. It's faster to type
  2. Unexpected levels make the line fail, which exposes malformed data
  3. \w+ can't match uppercase
  4. Named groups require it

In Python's verbose mode, how do you match a literal space?

  1. Just type a space
  2. \ or [ ]
  3. \s only
  4. %20