Regular Expression

Hi all ,

I’m trying to replace only one string in the content , but the -replace command is replacing all of the match strings .

How can I pointed to only replace the first word that is matched instead of all words .

I would appreciate any help .


Mariusz .

There are a few ways to do that. I don’t like to use PowerShell’s -replace operator in this instance most of the time, because it has no way of specifying the number of replacements to perform. Instead, I call the underlying .NET Framework methods directly:

$string = 'The dog jumped over a dog to eat a hot dog.'
([regex]'dog').Replace($string, 'cat', 1)

If you want to use the -replace operator (which always performs a global replacement), then what you’d need to do is modify your pattern so it only matches the first instance of ‘dog’, or so that it matches everything, but replaces only one. Here are two options for doing that (and you’ll see why I prefer calling the Replace() method on a regex object instead):

$string = 'The dog jumped over a dog to eat a hot dog.'

$string -replace '(?<!.*dog.*)dog', 'cat'

$string -replace '^(.*?)dog(.*)$', '$1cat$2'

Thanks DAVE !! That is awesome :smiley: , First example looks more easy . I still need to learn more about regular expressions .