Abhijit
Abhijit

Reputation: 35

how to match all the strings having a particular pattern between two other strings using regex

I want to extract all strings from "Timestamp:" to "Parameter"

If I encounter any String ending with "Exception:" between "a\n" to "site" where '-' is the character preceding "\nTimestamp"

Input:

aaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Timestamp: 8/10/2017 3:11:53 AM

Message: System.ArgumentNullException: site parameter is missing from distributed cache namespace
Parameter name: site

Output:

Timestamp: 8/10/2017 3:11:53 AM

Message: System.ArgumentNullException: site parameter is missing from distributed cache namespace

Basically, I want to detect any Exception in my .log file and show the Timestamp when that exception occured. Would be happy if the regex works from the Windows Command Line. Thank you.

Upvotes: 1

Views: 43

Answers (2)

LukStorms
LukStorms

Reputation: 29677

Here's a regex that'll capture the timestamp and the message content in capture group 1 & 2 :

/^Timestamp:\s*(.*)$\s*Message:\s*(.*)$/gm

You can test it here

Example of powershell running the regex on the command line for a file "test.txt":

powershell -Command "$f=[io.file]::ReadAllText('test.txt'); $f |Select-String '(?m)^Timestamp:\s*(.*)$\s*Message:\s*(.*)$' -AllMatches |%{$_.Matches}|%{$_.Groups[1].Value+': '+$_.Groups[2].Value}"

Upvotes: 0

marvel308
marvel308

Reputation: 10458

you can use the regex

(Timestamp.*\n*.*Exception.*\n*)(?=Parameter)

which would capture your result in the first group, see the demo here

Upvotes: 1

Related Questions