Lasse .ps1
Lasse .ps1

Reputation: 9

RegEx to find numbers in a string using PowerShell

Imagine having 500 string like this with different dates:

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

Given that this is a String and I'am using powershell. I need to treat the date (02/05/2014) as an object, so I can use operatators (-lt -gt).

Is the only way doing this is using RegEx, and in this case - can anyone help me finding the first 6 numbers (which change every time) using regEx.

Upvotes: 0

Views: 62

Answers (1)

Moerwald
Moerwald

Reputation: 11254

>$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

If you need to parse the date string with another format you can do:

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

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

Hope that helps

Upvotes: 2

Related Questions