Regular Expression issues


I have a variable $datestring which contains a mixture of text and a date. This was pulled from the description field in AD. I would like to evaluate that and convert to date.

I tested a regular expression ‘\d{1,2}/\d{1,2}/\d{4}$’ that extracted the date.
I first tested it on a fully defined text expression to see if it worked.

like so

 ([regex]::Match('Disabled 16/3/2016', '\d{1,2}\/\d{1,2}\/\d{4}$' )).value

Answer was correct.

So I thought i could do

 [regex]::Match('$datestring', '\d{1,2}\/\d{1,2}\/\d{4}$' )

But all I got was false.

How can I get the variable contents be placed in the regex so it can evaluate it? What am i missing?

Many thanks,

Wei-Yen Tan

You’ve put single quotes around $datestring, which is causing that text to be searched literally (not the value of the variable). If it’s already a string, no need to quote it:

[regex]::Match($datestring, '\d{1,2}\/\d{1,2}\/\d{4}$')

You could also just use PowerShell’s built-in operator instead of having to call the .net methods:

$datestring -match '\d{1,2}\/\d{1,2}\/\d{4}$'

Thanks Dave,

I have tried using the variables without quotes so it looks like this:
$datestring -match ‘\d{1,2}/\d{1,2}/\d{4}$’

I revised my variable so it is listed like this:

$datestring = get-aduser breyes -Properties description | Select -expandproperty description

So it will expand the properties as a string. Still no dice so I am a bit confused. When I run Get-Member the type is a string.

$testString ="This account was created on 02/02/2016 by Bob."
$pattern = [regex]"(?'date'\d{1,2}/\d{1,2}/\d{4})"

if ($testString -match $pattern)
    # examples of using the match, named and positional captures
    "It happened on $($Matches[0])"

This pattern: ‘\d{1,2}/\d{1,2}/\d{4}$’ requires that the date be the very last thing in the string (that’s what the $ anchor at the end means). If your description field has any other characters after the date, even if they’re just whitespace, then it wouldn’t match. There also can’t be any whitespace within the date, such as ‘1 / 5 / 2014’. If you need to handle those sorts of things, then the pattern needs to be tweaked slightly.

Hi Dave/Bob,

That was easy to fix. I just took off the ? and it works as it should.

Thanks for that. Understanding Regexes is a whole new world…

This regular expression may be easier to read.

# Culture is en-GB (UK)
$date = 'Disabled 15/3/2016' 
If ($date -match "Disabled (?'date'.*\d{4})"){Get-Date -Date $Matches['date']}