我正在使用Powershell搜索一个大文件,以查找包含mm-dd-yyyy格式的所有字符串。然后,我需要提取该字符串以确定该日期是否为有效日期。该脚本的大部分工作,但它返回了太多的结果,并没有提供所有我想要的信息。文件中有像012-34-5678这样的字符串,因此我会得到一个失败的,12-34-5678的值将作为一个无效的日期返回。我也不能返回发现无效日期的行号。有没有人可以看看我下面的脚本,看看我可能做错了什么?
这两个注释掉的行将返回字符串号和在该行上找到的整个字符串,但是我不知道如何仅从该行中提取mm-dd-yyyy部分并确定它是否为有效日期。
任何帮助都将不胜感激。谢谢。
#$matches = Select-String -Pattern $regex -AllMatches -Path "TestFile_2013_01_06.xml" |
#$matches | Select LineNumber,Line
$regex = "\d{2}-\d{2}-\d{4}"
$matches = Select-String -Pattern $regex -AllMatches -Path "TestFile_2013_01_06.xml" |
Foreach {$_.Matches | Foreach {$_.Groups[0] | Foreach {$_.Value}}}
foreach ($match in $matches) {
#$date = [datetime]::parseexact($match,"MM-dd-yyyy",$null)
if (([Boolean]($match -as [DateTime]) -eq $false ) -or ([datetime]::parseexact($match,"MM-dd-yyyy",$null).Year -lt "1800")) {
write-host "Failed $match"
}
}发布于 2013-01-25 23:57:38
行号在Select-String输出的对象上可用,但是您没有在$matches中捕获它。试试这个:
$matchInfos = @(Select-String -Pattern $regex -AllMatches -Path "TestFile_2013_01_06.xml")
foreach ($minfo in $matchInfos)
{
#"LineNumber $($minfo.LineNumber)"
foreach ($match in @($minfo.Matches | Foreach {$_.Groups[0].value}))
{
if ($match -isnot [DateTime]) -or
([datetime]::parseexact($match,"MM-dd-yyyy",$null).Year -lt "1800")) {
Write-host "Failed $match on line $($minfo.LineNumber)"
}
}
}发布于 2013-01-25 23:57:29
通过使正则表达式更健壮,可以在正则表达式本身中执行大量验证:
$regex = "(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)[0-9]{2}"上面的代码匹配从1900年1月1日到2099年12月31日之间的任何日期,并接受正斜杠、短划线、空格和圆点作为日期分隔符。它不会拒绝无效的日期,如2月30日或31日、11月31日等。
发布于 2013-01-26 04:14:48
我可能只会尝试将Select-String的结果与实际的匹配结果联系起来。我没有包含检查日期是否足够“新”的条件:
Select-String -Pattern '\d{2}-\d{2}-\d{4}' -Path TestFile_2013_01_06.xml -AllMatches |
ForEach-Object {
$Info = $_ |
Add-Member -MemberType NoteProperty -Name Date -Value $null -PassThru |
Add-Member -MemberType NoteProperty -Name Captured -Value $null -PassThru
foreach ($Match in $_.Matches) {
try {
$Date = [DateTime]::ParseExact($Match.Value,'MM-dd-yyyy',$null)
} catch {
$Date = 'NotValid'
} finally {
$Info.Date = $Date
$Info.Captured = $Match.Value
$Info
}
}
} | Select Line, LineNumber, Date, Captured当我在一些样本数据上尝试它时,我得到了这样的结果:
Line LineNumber Date Captured
---- ---------- ---- --------
Test 12-12-2012 1 2012-12-12 00:00:00 12-12-2012
Test another 12-40-2030 2 NotValid 12-40-2030
20-20-2020 And yet another 01-01-1999 3 NotValid 20-20-2020
20-20-2020 And yet another 01-01-1999 3 1999-01-01 00:00:00 01-01-1999https://stackoverflow.com/questions/14525236
复制相似问题