Replacing only the first occurrence of a word in a string

前端 未结 2 1952
没有蜡笔的小新
没有蜡笔的小新 2020-12-03 22:48

I am having some issues with regular expression mainly because I think the information I can find is not specifically for powershell and all the samples I have tried either

相关标签:
2条回答
  • 2020-12-03 22:55

    You could capture everything bevore and behind and replace it:

    'My name is Bob, her name is Sara.' -replace '(.*?)name(.*)', '$1baby$2'
    
    0 讨论(0)
  • 2020-12-03 23:12

    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
    
    0 讨论(0)
提交回复
热议问题