Find multiple matches

by May 19, 2011

When you want to find matches based on regular expressions, PowerShell will only support the -match operator which finds the first match. There does not seem to be a -matches operator that returns all matches.

You can use Select-Object like so to find all matches:

"1 2 3 4 5" | Select-String -AllMatches -Pattern '\d' |
Select-Object -ExpandProperty Matches |
Select-Object -ExpandProperty Value

Here is a sample text with some e-mail addresses. Use Select-Object to find all of them for you:

"My email is tobias.weltner@email.de and also tobias@powershell.de" |
Select-String -AllMatches '\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b' |
Select-Object -ExpandProperty Matches | Select-Object -ExpandProperty Value

Results:

tobias.weltner@email.de
tobias@powershell.de

 

Twitter This Tip!
ReTweet this Tip!