假設我有一個檔案名字串,例如:
test_ABC_19000101_010101.987.txt,
其中“測驗”可以是空格、字符、數字等的任意組合。我希望19000101_010101使用 Powershell提取部分(日期和時間)。目前我正在分配-split "_ABC_"給一個變數并取陣列的第二個元素。然后我隨后將拆分此字串。有沒有辦法一次性完成這個任務?
聚苯乙烯
"_ABC_" 是恒定的,在所有檔案名實體中都保持不變。
uj5u.com熱心網友回復:
一個更簡潔 - 盡管可能更模糊 - 替代Santiago Squarzon 的有用答案:
# Construct a regex that consumes the entire file name while
# using capture groups for the parts of interest.
$re = '. _ABC_(\d{4})(\d{2})(\d{2})_(\d{2})(\d{2})(\d{2})\.(\d{3})\.. '
[datetime] (
# In the replacement string, use $1, $2, ... to refer to what the
# first, second, ... capture group captured.
'test_ABC_19000101_010101.987.txt' -replace $re, '$1-$2-$3T$4:$5:$6.$7'
)
輸出:
Monday, January 1, 1900 1:01:01 AM
該-replace操作產生 string '1900-01-01T01:01:01.987',這是一種(文化不變)格式,您可以按原樣使用[datetime]強制轉換。
請注意,通過Get-ChildItem呼叫作為輸入,您可以通過提供$_.BaseName而不是$_.Name作為-replaceLHS來稍微簡化正則運算式,這樣就無需匹配正則運算式中的擴展名( .\. )。
uj5u.com熱心網友回復:
這個正則運算式似乎有點矯枉過正,但我??認為它應該可以作業,只要它_ABC_是常數并且有一個_將日期與時間.分開并將時間與毫秒分開:
$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
)
}
有關詳細資訊,請參閱https://regex101.com/r/8oSpqf/1。
uj5u.com熱心網友回復:
如果檔案名中永遠不會有多個序列顯示為時間戳(8 位、_、6 位,那么您可以匹配該數字模式。
PS C:\> 'test_ABC_19000101_010101.987.txt' -match '^.*ABC_(\d{8}_\d{6})\..*'
True
PS C:\> $Matches
Name Value
---- -----
1 19000101_010101
0 test_ABC_19000101_010101.987.txt
PS C:\> $Matches[1]
19000101_010101
您將使用檔案名而不是顯式字串。
如果您想從中獲取 [System.DateTime]:
PS C:\> [datetime]::ParseExact($Matches[1], 'yyyyMMdd_HHmmss', $null)
Monday, January 1, 1900 01:01:01
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/388238.html
