Replacing only the first occurrence of a word in a string

Solution 1:

One way to replace n times:

$test = "My name is Bob, her name is Sara."
[regex]$pattern = "name"
$pattern.replace($test, "baby", 1) 

> My baby is Bob, her name is Sara

Solution 2:

You could capture everything bevore and behind and replace it:

'My name is Bob, her name is Sara.' -replace '(.*?)name(.*)', '$1baby$2'