Regular Expression

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of Mariusz Serwin Mariusz Serwin 2 years, 4 months ago.

  • Author
    Posts
  • #17557
    Profile photo of Mariusz Serwin
    Mariusz Serwin
    Participant

    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 .

  • #17558
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    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'
    
  • #17586
    Profile photo of Mariusz Serwin
    Mariusz Serwin
    Participant

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

You must be logged in to reply to this topic.