PowerShell Regular Expressions Replace text with dynamic value using a MatchEvalutor


Example

Sometimes you need to replace a value matching a pattern with a new value that's based on that specific match, making it impossible to predict the new value. For these types of scenarios, a MatchEvaluator can be very useful.

In PowerShell, a MatchEvaluator is as simple as a scriptblock with a single paramter that contains a Match-object for the current match. The output of the action will be the new value for that specific match. MatchEvalutor can be used with the [Regex]::Replace() static method.

Example: Replacing the text inside () with it's length

#Sample text
$text = @"
This is (a) sample
text, this is
a (sample text)
"@
    
#Sample pattern: Content wrapped in ()
$pattern = '(?<=\().*?(?=\))'

$MatchEvalutor = {
    param($match)

    #Replace content with length of content
    $match.Value.Length

}

Output:

> [regex]::Replace($text, $pattern, $MatchEvalutor)

This is 1 sample
text, this is
a 11

Example: Make sample upper-case

#Sample pattern: "Sample"
$pattern = 'sample'

$MatchEvalutor = {
    param($match)

    #Return match in upper-case
    $match.Value.ToUpper()

}

Output:

> [regex]::Replace($text, $pattern, $MatchEvalutor)

This is (a) SAMPLE
text, this is
a (SAMPLE text)