Regex patterns/Dates & times

Log line timestamp

Pulls the timestamp out of a bracketed log line, one capture group.

/^\[(\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2})\]/gm
Open it in Rex

The problem

Extract the timestamp from the start of each line in a bracketed log.

How it reads

start\[1\drepeat-\drepeat-\drepeat[ T]\drepeat:\drepeat:\drepeat\]

Follow the line from left to right — every path you can trace is a string this pattern matches.

  1. ^\[(\d{4}-\d{2}-\d{2}…In order:
  2. ^The start of the text (or of a line with the m flag)
  3. \[The character "["
  4. (\d{4}-\d{2}-\d{2}[ T…Capture group 1:
  5. \d{4}-\d{2}-\d{2}[ T]…In order:
  6. \d{4}A digit, exactly 4 times, as many as possible
  7. -The character "-"
  8. \d{2}A digit, exactly 2 times, as many as possible
  9. -The character "-"
  10. \d{2}A digit, exactly 2 times, as many as possible
  11. [ T]Any one of: a space or "T"
  12. \d{2}A digit, exactly 2 times, as many as possible
  13. :The character ":"
  14. \d{2}A digit, exactly 2 times, as many as possible
  15. :The character ":"
  16. \d{2}A digit, exactly 2 times, as many as possible
  17. \]The character "]"

Matches

  • [2024-06-01 09:30:00] INFO started
  • [2024-06-01T09:30:02] WARN

Does not match

  • no timestamp here
  • 2024-06-01 09:30:00 INFO

Where it bites

  • Square brackets have to be escaped outside a character class, or they open one.
  • The capture group is inside the brackets, so the match includes them and group 1 does not — that is usually what you want.
  • The m flag makes ^ mean "start of a line". Without it only the first log line ever matches.

More dates & times patterns