Help with Powershell Regular Expression

Steven Neville 21 Reputation points
2022-11-22T16:32:03.603+00:00

I was asked to write a regular expression for "08 Nov 2022". The day has to be 2 digits, the month has to be 3 letters, and the year has to be 4 digits. You also have to specify a space inbetween the day, month, and year

I came up with: "08 Nov 2022" -match '[0-3][0-9]\s[jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec]\s\d{4}'

When this is executed, it will return false.

I tried the following, each returned true:

"08" -match '[0-3][0-9]'
"Nov" -match '[jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec]'
"2022" -match '\d{4}'
"08 Nov" -match '[0-3][0-9]\s[jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec]'
"Nov 2022" -match '[jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec]\s\d{4}'

But when you combine everything to validate day, month, and year; it returns false.

Does anyone have an idea why this is happening? I have a few friends also looking into this but they don't have an answer for me.

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,449 questions
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 45,671 Reputation points
    2022-11-22T16:45:26.627+00:00

    The square brackets are used to include a set of characters (like "[A-Z]"). Replace those with parentheses:

    "08 Nov 2022" -match '[0-3][0-9]\s(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\s\d{4}'  
    

0 additional answers

Sort by: Most helpful