Find multiple matches

Share |

Join PowerShell.com!
Subscribe to Feed

PowerShell eBook
Sign up for
Your PowerTip of the Day:

Award-winning PowerShellPlus


Admin Guide to PowerShell Remoting


Mastering PowerShell eBook

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!


Posted May 19 2011, 08:00 AM by ps1
Copyright 2012 PowerShell.com. All rights reserved.