【问题标题】:How to print substring containing time stamp in the format 'day dd/mm/yyy hh:mm:ss.ms' from string using select-string pattern of regex expression?如何使用正则表达式的选择字符串模式从字符串中打印包含格式为“day dd/mm/yyyy hh:mm:ss.ms”的时间戳的子字符串?
【发布时间】:2019-12-17 15:12:55
【问题描述】:

我想从具有格式 "day dd/mm/yyy hh:mm:ss.ms" 的时间戳的字符串中打印子字符串

例如

“Thu 12/05/2016 12:11:14.84 已成功更新驱动程序”

我只想获取行的时间戳部分。如何使用正则表达式和选择字符串来实现这一点?

【问题讨论】:

    标签: powershell


    【解决方案1】:

    你是说ddd dd/MM/yyyy HH:mm:ss.ff吗?

    由于该格式产生固定长度的输出(我认为 - date separatortime separator 的类型为 String,因此可以想象它们可能是多个 Chars 长,尽管容纳特定于文化的分隔符会使用正则表达式也很棘手)您可以从前 26 个字符中提取时间戳...

    PS> $text = 'Thu 12/05/2016 12:11:14.84 Updated drivers successfully'
    PS> $timestampText = $text.Substring(0, 26)
    PS> $timestamp = [DateTime]::ParseExact($timestampText, 'ddd dd/MM/yyyy HH:mm:ss.ff', $null)
    PS> $timestampText, $timestamp
    Thu 12/05/2016 12:11:14.84
    
    Thursday, May 12, 2016 12:11:14 PM
    

    否则你可以使用这样的正则表达式...

    PS> $text = 'Thu 12/05/2016 12:11:14.84 Updated drivers successfully'
    PS> $pattern = '^[a-z]{3}\s+\d{2}/\d{2}/\d{4}\s+\d{2}:\d{2}:\d{2}\.\d{2}'
    PS> $format = 'ddd dd/MM/yyyy HH:mm:ss.ff'
    PS> if ($text -match $pattern) { $Matches[0]; [DateTime]::ParseExact($Matches[0], $format, $null) }
    Thu 12/05/2016 12:11:14.84
    
    Thursday, May 12, 2016 12:11:14 PM
    

    我使用\s+ 表示这两个空格...只是因为,但您也可以使用文字空格代替。

    您还可以消除模式中重复的\d{2}/\d{2}/\d{2}:\d{2}:...

    PS> $pattern = '^[a-z]{3}\s+(?:\d{2}/){2}\d{4}\s+(?:\d{2}:){2}\d{2}\.\d{2}'
    

    @Vishal's answer 的启发,提取第三个空格之前的所有内容,您可以通过以下两种方式检索其中一种...

    PS> $text = 'Thu 12/05/2016 12:11:14.84 Updated drivers successfully'
    PS> ($text -split ' ', 4 | Select-Object -First 3) -join ' '
    Thu 12/05/2016 12:11:14.84
    PS> if ($text -match '^\S+ \S+ \S+') { $Matches[0] }
    Thu 12/05/2016 12:11:14.84
    

    【讨论】:

    • 谢谢@BACON,得到了想要的输出
    【解决方案2】:
    Set-Variable -Name "TEST" -Value "Thu 12/05/2016 12:11:14.84 Updated drivers successfully"
    
    $Timestamp = $TEST.Split(" ")[0,1,2]
    
    Write-Host $Timestamp
    
    
    
    Thu 12/05/2016 12:11:14.84
    

    【讨论】:

    • 啊,我没想到。 +1。 “第三个空格之前的所有内容”可能比固定字符偏移更具弹性。这可以通过($text -split ' ', 4 | Select-Object -First 3) -join ' '$text -match '^\S+ \S+ \S+' 获得。
    【解决方案3】:

    要获取子字符串时间戳,请执行以下操作:

    "The string" -match "..[:]..[:]..[.].."
    $matches[0]
    

    【讨论】:

    • 您提供的答案是不确定的。你能详细说明一下吗?
    • 它显示的是 dd:hh:mm.ms" 格式。我们怎样才能得到完整的 "day dd/mm/yyyy hh:mm:ss.ms"?
    猜你喜欢
    • 2021-07-16
    • 2012-05-15
    • 2018-07-31
    • 1970-01-01
    • 2011-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多