How to get the captured groups from Select-String? How to get the captured groups from Select-String? powershell powershell

How to get the captured groups from Select-String?


Have a look at the following

$a = "http://192.168.3.114:8080/compierews/" | Select-String -Pattern '^http://(.*):8080/(.*)/$' 

$a is now a MatchInfo ($a.gettype()) it contain a Matches property.

PS ps:\> $a.MatchesGroups   : {http://192.168.3.114:8080/compierews/, 192.168.3.114, compierews}Success  : TrueCaptures : {http://192.168.3.114:8080/compierews/}Index    : 0Length   : 37Value    : http://192.168.3.114:8080/compierews/

in the groups member you'll find what you are looking for so you can write :

"http://192.168.3.114:8080/compierews/" | Select-String -Pattern '^http://(.*):8080/(.*)/$'  | % {"IP is $($_.matches.groups[1]) and path is $($_.matches.groups[2])"}IP is 192.168.3.114 and path is compierews


According to the powershell docs on Regular Expressions > Groups, Captures, and Substitutions:

When using the -match operator, powershell will create an automatic variable named $Matches

PS> "The last logged on user was CONTOSO\jsmith" -match "(.+was )(.+)"

The value returned from this expression is just true|false, but PS will add the $Matches hashtable

So if you output $Matches, you'll get all capture groups:

PS> $MatchesName     Value----     -----2        CONTOSO\jsmith1        The last logged on user was0        The last logged on user was CONTOSO\jsmith

And you can access each capture group individually with dot notation like this:

PS> "The last logged on user was CONTOSO\jsmith" -match "(.+was )(.+)"PS> $Matches.2CONTOSO\jsmith

Additional Resources:


Late answer, but to loop multiple matches and groups I use:

$pattern = "Login:\s*([^\s]+)\s*Password:\s*([^\s]+)\s*"$matches = [regex]::Matches($input_string, $pattern)foreach ($match in $matches){    Write-Host  $match.Groups[1].Value    Write-Host  $match.Groups[2].Value}