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.
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.
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.
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" .
-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.
You can use the -match
operator to reformulate your command as:
some-command | Foreach-Object { if($_ -match '^(//[^#]*)') { some-other-command $($matches[1])}}
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
You could try this:
Get-Content foo.txt | foreach { some-othercommand [regex]::match($_,'^(//[^#]*)').value }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With