Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 456
scobi Avatar asked Jun 18 '09 05:06

scobi


People also ask

Can you do regex in PowerShell?

One of the most useful and popular PowerShell regex operators is the match and notmatch operators. These operators allow you to test whether or not a string contains a specific regex pattern. If the string does match the pattern, the match operator will return a True value.

How do you use regex expressions in PowerShell?

A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. They can be used to search, edit, or manipulate text and data. Matches the beginning of the line. Matches the end of the line.

What is a capturing group regex?

Capturing groups are a way to treat multiple characters as a single unit. They are created by placing the characters to be grouped inside a set of parentheses. For example, the regular expression (dog) creates a single group containing the letters "d" "o" and "g" .

What is Cmatch in PowerShell?

-cmatch makes the operation case sensitive. -notmatch returns true when there is no match. The i and c variants of an operator is available for all comparison operators.


3 Answers

You can use the -match operator to reformulate your command as:

some-command | Foreach-Object { if($_ -match '^(//[^#]*)') { some-other-command $($matches[1])}}
like image 65
Bas Bossink Avatar answered Oct 22 '22 22:10

Bas Bossink


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

like image 38
Joe Avatar answered Oct 22 '22 22:10

Joe


You could try this:

Get-Content foo.txt | foreach { some-othercommand [regex]::match($_,'^(//[^#]*)').value } 
like image 33
Shay Levy Avatar answered Oct 22 '22 22:10

Shay Levy