Alex Rivera | Logout

Is there a shorter way to pull groups out of a Powershell regex?

Asked 2009-06-18T05:37:01.217
18

In PowerShell I find myself doing this kind of thing over and over again for matches:

some-command | select-string '^(//[^#]*)' |
     %{some-other-command $_.matches[0].groups[1].value}

So basically - run a command that generates lines of text, and for each line I want to run a command on a regex capture inside the line (if it matches). Seems really simple. The above works, but is there a shorter way to pull out those regex capture groups? Perl had $1 and so on, if I remember right. Posh has to have something similar, right? I've seen "$matches" references on SO but can't figure out what makes that get set.

I'm very new to PowerShell btw, just started learning.

Edit
Report

1 Answer

8

Named Replacement

'foo bar' -replace '(?<First>foo).+', '${First}'

Returns: foo

Unnamed Replacement

 'foo bar' -replace '(foo).+(ar)', '$2 z$2 $1'

Returns: ar zar foo

answered 2012-03-07T19:22:25.700

Your Answer