Reputation: 23
$data = 'TimeStamp=2021-06-20 02:07:43.7841 Level=INFO TraceId=vQCGLkvAqFGEfrIR Message=End processing HTTP request after 7.5217ms - OK'
$test1 = [System.Text.RegularExpressions.Regex]::Matches($data , "(?<=TimeStamp=)[^\s]+").Value
Anyone know how to extract the full timestamp out of the string?. I only able to extract the date (2021-06-20).
i had tried another regex format(format2 as below) also, but it hit an error of (Exception calling "Matches" with "2" argument(s): "parsing "(?<=TimeStamp=)[\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}(?.\d{3}\b)?]+" - Cannot include class \d in character range.")
Format 2:
$test1 = [System.Text.RegularExpressions.Regex]::Matches($data , "(?<=TimeStamp=)[\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}(?.\d{3}\b)?]+").Value
Upvotes: 1
Views: 199
Reputation: 437588
If you can rely on all input strings to have the format shown in the question, a perhaps conceptually simpler alternative (though slightly slower) is to use -split
, the regex-based string-splitting operator:
# Sample input.
$data = 'TimeStamp=2021-06-20 02:07:43.7841 Level=INFO TraceId=vQCGLkvAqFGEfrIR Message=End processing HTTP request after 7.5217ms - OK'
# This outputs '2021-06-20 02:07:43.7841', as intended.
# Note:
# * -csplit is the case-*sensitive* variant of the case-insensitive -split
($data -csplit '^TimeStamp=| Level=')[1]
Upvotes: 1
Reputation: 626794
You can match two non-whitespace chunks after TimeStamp=
:
> $test1 = [regex]::Match($data , "(?<=TimeStamp=)\S+ \S+").Value
> $test1
2021-06-20 02:07:43.7841
Alternatively, you can also use
> $test1 = [regex]::Match($data , "(?<=TimeStamp=)\d{4}-\d{1,2}-\d{1,2} \d{1,2}:\d{1,2}:\d{2}\.\d+").Value
> $test1
2021-06-20 02:07:43.7841
Note that since you want to get the first match only, you do not need Regex.Matches
, you can use Regex.Match
.
Another way to get the first match here is using -match
:
> $data -match "(?<=TimeStamp=)\S+ \S+" | Out-Null
> $matches[0]
2021-06-20 02:07:43.7841
Upvotes: 1