Search code examples
syntaxnotepad++syntax-highlightinghighlighting

Syntax Highlighting in Notepad++: how to highlight timestamps in log files


I am using Notepad++ to check logs. I want to define custom syntax highlighting for timestamps and log levels. Highlighting logs levels works fine (defined as keywords). However, I am still struggling with highlighting timestamps of the form

06 Mar 2014 08:40:30,193

Any idea how to do that?


Solution

  • If you just want simple highlighting, you can use Notepad++'s regex search mode. Open the Find dialog, switch to the Mark tab, and make sure Regular Expression is set as the search mode. Assuming the timestamp is at the start of the line, this Regex should work for you:

    ^\d{2}\s[A-Za-z]+\s\d{4}\s\d{2}:\d{2}:\d{2},[\d]+
    

    Breaking it down bit by bit:
    ^ means the following Regex should be anchored to the start of the line. If your timestamp appears anywhere but the start of a line, delete this.
    \d means match any digit (0-9). {n} is a qualifier that means to match the preceding bit of Regex exactly n times, so \d{2} means match exactly two digits.
    \s means match any whitespace character.
    [A-Za-z] means match any character in the set A-Z or the set a-z, and the + is a qualifier that means match the preceding bit of Regex 1 or more times. So we're looking for an alphabetic character sequence containing one or more alphabetic characters.
    \s means match any whitespace character.
    \d{4} is just like \d{2} earlier, only now we're matching exactly 4 digits.
    \s means match any whitespace character.
    \d{2} means match exactly two digits.
    : matches a colon.
    \d{2} matches exactly two digits.
    : matches another colon.
    \d{2} matches another two digits.
    , matches a comma.
    [\d]+ works similarly to the alphabetic search sequence we set up earlier, only this one's for digits. This finds one or more digits.

    When you run this Regex on your document, the Mark feature will highlight anything that matches it. Unlike the temporary highlighting the "Find All in Document" search type can give you, Mark highlighting lasts even after you click somewhere else in the document.