How do you extract the value of a regex backreference/match in Powershell How do you extract the value of a regex backreference/match in Powershell powershell powershell

How do you extract the value of a regex backreference/match in Powershell


I don't know why your version doesn't work. It should work. Here is an uglier version that works.

$p = "subject=([A-Z\.]+),"select-string -path *.txt -pattern $p | % {$_ -match $p > $null; $matches[1]}

Explanation:

-match is a regular expression matching operator:

>"foobar" -match "oo.ar"True

The > $null just suppresses the True being written to the output. (Try removing it.) There is a cmdlet that does the same thing whose name I don't recall at the moment.

$matches is a magic variable that holds the result of the last -match operation.


In PowerShell V2 CTP3, the Matches property is implemented. So the following will work:

select-string -path *.txt -pattern "subject=([A-Z\.]+)," | %{ $_.Matches[0].Groups[1].Value }


Yet another option

gci *.txt | foreach { [regex]::match($_,'(?<=subject=)([^,]+)').value }