Search code examples
c#.netregexpowershell

Regex multiline log


I'd like to use a .NET / Powershell regex to search a log for Success status at a particular location, say ABC.

If I use the following pattern: "(?ms)A status: Success.*?Location: " with global (aka AllMatches) then it finds all log record with a status of Success at any location.

If I try to narrow it down by appending ABC to the pattern, then the match is too greedy and goes from the Success on line 18 all the way to the ABC on line 28.

I gave up and used a pattern that is more explicit (it grabs the full log record and seems to work because I specify a pattern between Success and Location):

(?sm)^\d([ \S]*\s{10}){3}A status: Success\s{2}([ \S]*\s{10}){2}Location: ABC[ \S]*

Is there a simpler pattern which can find what I'm after?

Note: I don't mind if the pattern grabs the full log record from date time (inclusive) to date time (exclusive),

Log file:

04/09/2018 06:31:59 AM [class | Info] some message received from 101592 (123.123.123.124)
        Request Id: 0 (Descriptor: 0, Operator Request Id: 0)
        A type: bar
        A status: Queued
        The id: 1E25
        Additional info: Inserted in queue at position 1 on device ABC
        Location: ABC, subarea: 2
04/09/2018 06:31:59 AM [class | Info] some message received from 102364 (123.123.123.123)
        Request Id: 0 (Descriptor: 0, Operator Request Id: 0)
        A type: bar
        A status: Queued
        The id: 1E25
        Additional info: Inserted in queue at position 1 on device ABC
        Location: ABC, subarea: 2
04/09/2018 06:31:59 AM [class | Info] some message received from 102364 (123.123.123.123)
        Request Id: 0 (Descriptor: 0, Operator Request Id: 0)
        A type: blah bit foo
        A status: Success
        The id: T908
        Additional info: 
        Location: DEF, subarea: 3
04/09/2018 06:32:00 AM [class | Info] some message received from 102364 (123.123.123.123)
        Request Id: 0 (Descriptor: 0, Operator Request Id: 0)
        A type: bar
        A status: Success
        The id: DG08
        Additional info: 
        Location: ABC, subarea: 1

Solution

  • Try with any of these:

    (?m)A status: Success(?:\n\h+.+)+Location: ABC

    (?m)A status: Success(?:\n\s+.+)+Location: ABC (if \h is not supported)

    Demo1

    Demo2

    Explained:

    Just limit the way you process extra data. Instead of a .*?, just use (?:\n\h+[^\n]+)+ (that is new line + some spaces at the beginning) That will disallow going through the next log entry, since the date starts at the begining of the line.

    (NOTE: I deleted the s modifier)