Home > OS >  Powershell RegEx assistance
Powershell RegEx assistance

Time:10-06

hoping somebody can help me out here. Current string:

$monthlist = @()
$monthlist = Get-ChildItem $place -Recurse -Directory -force `
| Where-Object { ($_.name -match '((\\0[1-9]|1[0-2])-(200[0-9]|20[1-4][0-9]|205[0-5]))') }

This returns in Powershell:

C:\temp\test\10-2021
C:\temp\test\12-2019
C:\temp\test\2019\12-2019
C:\temp\test\2020\11-2020

But not:

c:\temp\test\08-2021 
c:\temp\test\09-2021

Using https://regex101.com/ and https://regexr.com/ they both say all 6 of the folders listed above should be matching.

I need the \ in the regex string due to there also being several folders such as the following that I do not want to match:

c:\temp\test\01-01-2021
c:\temp\test\05-25-2020

I'm not the best at RegEx and I'm hoping somebody can spot my error pretty quick

CodePudding user response:

The \\ in front of the first group prevents matching against names that start with 0.

If you're worried about matching a substring that's part of a larger string (like 01-2021 in 01-01-2021), make sure you anchor the pattern against the ^ start-of-string and $ end-of-string metacharacters:

... | Where-Object { ($_.name -match '^((0[1-9]|1[0-2])-(200[0-9]|20[1-4][0-9]|205[0-5]))$') }
  • Related