简体   繁体   English

在Powershell变量中查找日期

[英]find a date in a powershell variable

I have parsed text file: 我已经解析了文本文件:

$Sel = select-string -pattern "Date=*" -path D:\\test_file.txt -List

and here is the result: 结果如下:

D:\test_file.txt:3: <aaa="000000" Date="2016-12-05"> <bbbbb="cccc" dddd="20161209" eeee="2016-12-09" fff="ggggg" hhhh="hhh" aaaa="1" bbbb="100" cccc="100">

I have tried to run regex on it 我试图在上面运行正则表达式

 $regex = "(19|20)[0-9]{2}[- -.](0[1-9]|1[012])[- -.](0[1-9]|[12][0-9]|3[01])"

to parse this again as 再次解析为

select-string -pattern $regex -InputObject $Sel

but that didn't work. 但这没用。 Do you have any ideas how to find the date in that above string? 您是否有任何想法如何在上述字符串中找到日期?

If the date pattern always is in the specified form Date="yyyy-MM-dd" , the most straightforward way is to look for that pattern. 如果日期模式始终采用指定的格式Date="yyyy-MM-dd" ,则最直接的方法是查找该模式。 No need to worry about 1900's and 2000's at all. 完全不必担心1900和2000。 Like so, 像这样

# Test data
$sel = 'D:\test_file.txt:3:< aaa="000000" Date="2016-12-05" >'

# Let's match date that starts with Date= literal
[regex]$rex = 'Date="(\d{4}-\d{2}-\d{2})"'

# Print the result if matched
if($rex.Match($sel).groups.count -eq 2) {
    $rex.Match($sel).groups[1].value
}

This should be correct: 这应该是正确的:

$sel -match $regex
$date = $matches[0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM