# Regular Expression 

**URL:** <https://forums.powershell.org/t/regular-expression/2893>\
**Category:** PowerShell Help\
**Created:** [July 28, 2014, 11:51pm UTC](https://forums.powershell.org/t/regular-expression/2893 "2014-07-28T23:51:53Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![mariusz-serwin-5](https://avatars.discourse-cdn.com/v4/letter/m/ecccb3/32.png) [@mariusz-serwin-5](https://forums.powershell.org/u/mariusz-serwin-5)\
**Post date:** [July 28, 2014, 11:51pm UTC](https://forums.powershell.org/t/regular-expression/2893/1 "2014-07-28T23:51:53Z")

</div>

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 .

Thanks

Mariusz .

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/flex019/uploads/powershell/original/1X/385e4f9fe133561ad30a814262fe0e0ae6bc3ef0.png) [@system](https://forums.powershell.org/u/system)\
**Post date:** [July 29, 2014, 12:14am UTC](https://forums.powershell.org/t/regular-expression/2893/2 "2014-07-29T00:14:24Z")

</div>

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'
```

---

<div class="post-metadata">

**Author:** ![mariusz-serwin-5](https://avatars.discourse-cdn.com/v4/letter/m/ecccb3/32.png) [@mariusz-serwin-5](https://forums.powershell.org/u/mariusz-serwin-5)\
**Post date:** [July 29, 2014, 7:07am UTC](https://forums.powershell.org/t/regular-expression/2893/3 "2014-07-29T07:07:15Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![dotnVo](https://avatars.discourse-cdn.com/v4/letter/d/4af34b/32.png) [@dotnVo](https://forums.powershell.org/u/dotnVo)\
**Post date:** [May 16, 2024, 8:47pm UTC](https://forums.powershell.org/t/regular-expression/2893/4 "2024-05-16T20:47:43Z")

</div>

Closed on May 16, 2024, 8:47pm UTC


