Replace text with a dynamic value using a MatchEvaluator

suggest change

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 a script block with one parameter: a Match object for the current match. Whatever the script block outputs becomes the replacement for that match. Pass it to the [regex]::Replace() static method.

Example: Replace the text inside () with its length.

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

$MatchEvaluator = {
    param($match)

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

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

This is 1 sample
text, this is
a 11

Example: Make sample upper-case

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

$MatchEvaluator = {
    param($match)

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

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

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents