Reputation: 43
Can someone help me with a regex to pull
Wed Oct 31
from the below
Date: Wed Oct 31 12:55:00 2018 -0500
Obviously the date will change day to day in the log.
Upvotes: 0
Views: 446
Reputation: 5938
You've asked for a regular expression but your example already shows a pitfall in the form of a timezone!
Just using a regular expression alone might get you the wrong day when the timezone offset pushes it across midnight. I'd recommend instead using [DateTime]::TryParseExact
instead and then using a Date string format to get it into the form you need:
$Line = "Date: Wed Oct 31 12:55:00 2018 -0500"
[DateTime] $Date = New-Object DateTime
$Success = [DateTime]::TryParseExact($Line,
"'Date: 'ddd MMM dd HH':'mm':'ss yyyy zzz",
[System.Globalization.CultureInfo]::InvariantCulture,
[System.Globalization.DateTimeStyles]::None,
[ref] $Date)
if ($Success) {
$Date.ToString("ddd MMM dd")
}
The above example prints out
Wed Oct 31
Upvotes: 7
Reputation: 7479
this aint a regex, but it seems to do the job ... [grin]
$FullDateString = 'Date: Wed Oct 31 12:55:00 2018 -0500'
# the `.Split()` version doesn't take into account random extra spaces in the source
# use the next line instead
#$DateString = $FullDateString.Split(' ')[1..3] -join ' '
$DateString = ($FullDateString -split '\s+')[1..3] -join ' '
$DateString
output = Wed Oct 31
what happened above ...
you may want to use a more flexible method and 1st convert to a [datetime]
object and then use .ToString()
with your preferred format.
Upvotes: 2
Reputation: 2245
Give a look here and here. With that, you can find a pretty easy regex to solve your problem!
Here's what I have:
$date = 'Date: Wed Oct 31 12:55:00 2018 -0500'
$date -replace "Date: (\w{3} \w{3} \d{2}) .*", '$1'
I don't know what you really want to do, so just change the regex as you want ;)
Upvotes: 1