Powershell正则表达式为mm-dd-yyyy

时间:2013-01-25 15:50:08

标签: regex powershell

我正在使用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"
    }
}

3 个答案:

答案 0 :(得分:2)

你可以在正则表达式中进行大量的验证,使其更加健壮:

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

上述内容与01/01/1900至12/31/2099之间的任何日期相匹配,并接受正斜杠,短划线,空格和点作为日期分隔符。它拒绝无效日期,如2月30日或31日,11月31日等。

答案 1 :(得分:1)

行号可用于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)"
        }
    }
 }

答案 2 :(得分:0)

我可能会尝试链接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-1999