Reputation: 521
I am new to powershell scripting and am not so good with Regex... I want to create a regular expression that will pick out time from the following text file...
gfskf dakdshadk daksdkdahkd daksdhasdkh () zadf sflh f.d / sd lhlfhlj f 12hrs:10mins:05sec fsfsf fsfjhsfjh
I want to get the hours so 12 and mins as 10 and seconds as 5.
$hour= [regex]::match($line,$hour_regex).Groups[1].Value
$mins= [regex]::match($line,$mins_regex).Groups[1].Value
$sec= [regex]::match($line,$sec_regex).Groups[1].Value
So essentially I need three regular expressions to extract the relevant data from the file.
Thanks in advance!
Upvotes: 2
Views: 538
Reputation: 126732
PS> $s -replace '^.+ (\d+hrs:\d+mins:\d+sec).*$','$1' -split '\D+' | where {$_}
12
10
05
Upvotes: 0
Reputation: 200273
Since nobody mentioned it yet, you can also use the -match
operator. The submatches can be accessed via the $matches
hashtable:
Get-Content "C:\path\to\your.txt" | ? {
$_ -match '(\d+)hrs:(\d+)mins:(\d+)sec'
} | % {
$h = $matches[1]
$m = $matches[2]
$s = $matches[3]
"{0}:{1}:{2}" -f ($h, $m, $s)
}
Upvotes: 1
Reputation: 60908
Just for fun:
$a = "gfskf dakdshadk daksdkdahkd daksdhasdkh () zadf sflh f.d / sd lhlfhlj f 12hrs:10mins:05sec fsfsf fsfjhsfjh"
$hour,$min, $sec = $a -split '(\d\d)' | ? { $_ -match '\d\d' }
Upvotes: 2
Reputation: 26140
if like me you are not at ease with regex you can use split function :
PS>$t="gfskf dakdshadk daksdkdahkd daksdhasdkh () zadf sflh f.d / sd lhlfhlj f 12hrs:10mins:05sec fsfsf fsfjhsfjh"
PS>$slices=$t.split(@(" ",":"))
$hours=($slices[12]).substring(0,2)
$mins=($slices[13]).substring(0,2)
$secs=($slices[14]).substring(0,2)
Upvotes: 0
Reputation: 10427
Use one regex:
$r = '(\d+)hrs:(\d+)mins:(\d+)sec'
$i = 'hlfhlj f 12hrs:10mins:05sec fsfsf f'
$result = [regex]::match($i,$r)
$hour = $result.Groups[1].Value
$mins = $result.Groups[2].Value
$sec = $result.Groups[3].Value
Upvotes: 2
Reputation: 72630
You can try :
$b= [regex]".* (\d*)hrs:(\d*)mins:(\d*)sec.*"
$hours=$b.Match($a).groups[1].value
$minutes=$b.Match($a).groups[2].value
$seconds=$b.Match($a).groups[3].value
Upvotes: 0
Reputation: 24071
Use regex capture groups. "(\d+)hrs:(\d+)mins:(\d+)sec"
will capture the numbers into groups that can be accessed. Save the results in a MatchCollection
to check the results. Like so,
$line = "sflh f.d / sd lhlfhlj f 12hrs:10mins:05sec fsfsf"
PS C:\> $mc = [regex]::match($line, "(\d+)hrs:(\d+)mins:(\d+)sec")
PS C:\> $mc.Groups[1].value
12
PS C:\> $mc.Groups[2].value
10
PS C:\> $mc.Groups[3].value
05
Upvotes: 0