13

I want to pass a function call(which returns a string) as a replacement string to Powershell's replace function such that each match found is replaced with a different string.

Something like -

$global_counter = 0
Function callback()
{
    $global_counter += 1   
    return "string" + $global_counter
}

$mystring -replace "match", callback()

Python allows this through 're' module's 'sub' function which accepts a callback function as input. Looking for something similar

Rupesh Yadav
  • 12,096
  • 4
  • 53
  • 70
Swapnil
  • 407
  • 4
  • 7

2 Answers2

25

Perhaps you are looking for Regex.Replace Method (String, MatchEvaluator). In PowerShell a script block can be used as MatchEvaluator. Inside this script block $args[0] is the current match.

$global_counter = 0
$callback = {
    $global_counter += 1
    "string-$($args[0])-" + $global_counter
}

$re = [regex]"match"
$re.Replace('zzz match match xxx', $callback)

Output:

zzz string-match-1 string-match-2 xxx
Roman Kuzmin
  • 40,627
  • 11
  • 95
  • 117
10

PowerShell does not (yet?) have support for passing a script block to the -replace operator. The only option here is to use [Regex]::Replace directly:

[Regex]::Replace($mystring, 'match', {callback})
Joey
  • 344,408
  • 85
  • 689
  • 683