Powershell, how much have you replaced?

I need to know how many replacements Powershell makes when using the -replace or Replace() operator. Or, if this is not possible, if it will replace it at all.

For example, in Perl, since the substitution operation returns the number of replacements made, and zero returns false, while a nonzero value true in a Boolean context, you can write:

 $greeting = "Hello, Earthlings"; if ($greeting ~= s/Earthlings/Martians/) { print "Mars greeting ready." } 

However, with Powershell, the operator and method return a new line. It seems that the operator provides some additional information if someone knows how to request it (for example, the captured groups are stored in a new variable that it creates in the current area), but I can’t find out how to get the score or success value.

I could just compare the values ​​before and after, but that seems completely ineffective.

+6
source share
3 answers

You are right, I do not think that you can squeeze out all the unnecessary because of the place. However, you can find the number of matches using Regex.Matches () . for example

 > $greeting = "Hello, Earthlings" > $needle = "l" > $([regex]::matches($greeting, $needle)).Length # cast explicitly to an array 3 

Then you can use the -replace operator, which uses the same matching mechanism.


Looking a little deeper, a Replace overload occurs, which accepts a MatchEvaluator delegate, which is called every time a match is performed, So, if we use this as a battery, it can count the number of replacements at a time.

 > $count = 0 > $matchEvaluator = [System.Text.RegularExpressions.MatchEvaluator]{$count ++} > [regex]::Replace("Hello, Earthlings","l",$matchEvaluator) > $count Heo, Earthings 3 
+8
source share

A version of the script that actually replaces things, not them:

 $greeting = "Hello, earthlings. Mars greeting ready" $counter = 0 $search = '\s' $replace = '' $evaluator = [System.Text.RegularExpressions.MatchEvaluator] { param($found) $counter++ Write-Output ([regex]::Replace($found, [regex] $search, $replace)) } [regex]::Replace($greeting, [regex] $search, $evaluator); $counter 

->

 > Hello,earthlings.Marsgreetingready > 4 
0
source share

Here is a complete functional example that saves the replacement behavior and counts the number of matches

 $Script:Count = 0 $Result = [regex]::Replace($InputText, $Regex, [System.Text.RegularExpressions.MatchEvaluator] { param($Match) $Script:Count++ return $Match.Result($Replacement) }) 
0
source share

All Articles