首页 > 解决方案 > RegEx 使用 PowerShell 在字符串中查找数字

问题描述

想象一下,有 500 个这样的字符串,日期不同:

The certificate has expired on 02/05/2014 15:43:01 UTC.

鉴于这是一个字符串,我正在使用 powershell。我需要将日期 (02/05/2014) 视为一个对象,因此我可以使用运算符 (-lt -gt)。

这样做的唯一方法是使用正则表达式,在这种情况下 - 任何人都可以帮助我使用正则表达式找到前 6 个数字(每次都会更改)。

标签: regexstringpowershell

解决方案


>$regexStr = "(?<date>\d{2}\/\d{2}\/\d{4})"
>$testStr = "The certificate has expired on 02/05/2014 15:43:01 UTC."
>$testStr -match $regexStr
# $Matches will contain the regex group called "date"
>$Matches.date
02/05/2014
>$date = Get-Date ($Matches.date)
>$date
Wednesday, February 5, 2014 12:00:00 AM

如果您需要使用另一种格式解析日期字符串,您可以执行以下操作:

 >$dateObj = [datetime]::ParseExact($Matches.date,”dd/MM/yyyy”,$null)
 >$dateObj.GetType()

  IsPublic IsSerial Name                                     BaseType
  -------- -------- ----                                     --------
  True     True     DateTime                                 System.ValueType

希望有帮助


推荐阅读