Say I have a filename string, something like:
test_ABC_19000101_010101.987.txt,
Where "test" could be any combination of white space, characters, numbers, etc. I wish to extract the 19000101_010101 part (date and time) with Powershell. Currently I am assigning -split "_ABC_" to a variable and taking the second element of the array. I am then splitting this string subsequent times. Is there a way to accomplish this in one go?
PS
"_ABC_" is constant, occurring unchanged in all instances of filename(s).
>Solution :
This regex seems an overkill but I think it should work, as long as _ABC_ is constant and there is a _ to separate the date from the time and a . to separate time from milliseconds:
$re = [regex]'(?<=_ABC_)(?<date>\d*)_(?<time>\d*)\.(?<millisec>\d*)(?=\.)'
@'
test_ABC_19000101_010101.987.txt
t' az@ 0est_ABC_20000101_090101.123.txt
tes8as712t_ABC_21000101_080101.456.txt
te098d $st_ABC_22000101_070101.789.txt
[test]_ABC_23000101_060101.101.txt
t?\est_ABC_24000101_050101.112.txt
'@ -split '\r?\n' | ForEach-Object {
$groups = $re.Match($_).Groups
$date = $groups['date']
$time = $groups['time']
$msec = $groups['millisec']
[datetime]::ParseExact(
"$date $time $msec",
"yyyyMMdd HHmmss fff",
[cultureinfo]::InvariantCulture
)
}
See https://regex101.com/r/8oSpqf/1 for details.