Regex matches in PowerShell


How to find regex matches using PowerShell

-match operator

In PowerShell the -match operator will evaluate whether a string matches a regular expression:

1
2
3
4
5
ps> "1234-56-789" -match "\d\d\d\d-\d\d-\d\d\d"
True

ps> "banana" -match "\d\d\d\d-\d\d-\d\d\d"
False

When you use the -match operator the variable $Matches is populated with all the matches:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
ps> "1234-56-789" -match "(\d+)-(\d+)-(\d+)"
True

ps> $Matches
Name                           Value
----                           -----
3                              789
2                              56
1                              1234
0                              1234-56-789

In particular if you used named matches you can retrieve the matched value by accessing a property on the $Matches variable with the same name:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
ps> "Tom Auger" -match "(?<first>\w+)\s(?<last>\w+)"; $Matches
Name                           Value
----                           -----
last                           Auger
first                          Tom
0                              Tom Auger

ps> $Matches.first
Tom

ps> $Matches.last
Auger

Equivalent of grep in PowerShell

To find regular expression matches in files in the current directory use the Select-String commandlet:

1
Select-String -Path *.* -Pattern "(?<first>\w+)\s(?<last>\w+)"

To search for a regular expression in files in the current directory and all subdirectories:

1
Get-ChildItem . -Recurse | Select-String -Pattern "(?<first>\w+)\s(?<last>\w+)"

Finding all matches

Use the -AllMatches switch on Select-String to find all pattern matches rather than just the first:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
ps> Select-String -InputObject "123-4-567-89" -Pattern "\d+" -AllMatches | 
Foreach-Object { $_.Matches } | 
Select-Object { $_.value }

 $_.value     
----------    
123           
4             
567           
89            

History of grep

Here’s an interesting video with Brian Kernighan about the history of grep.

g/re/p - global / regular expression / print

References