Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

powershell - Replacing only the first occurrence of a word in a string

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 error or don't work as intended. I am trying to replace the first occurrence of a word in a string with another word but not replace any other occurrences of that word. for an example take the string:

My name is Bob, her name is Sara.

I would like to replace the first occurrence of name with baby so the resulting string would be

My baby is Bob, her name is Sara.

I have been working in https://regex101.com/ to try to build and see what is selected as I go but as I said none of these have a powershell flavor of regex. In that I can just turn off the global flag and it seems to select the first occurrence but not in powershell. So I am really at a loss of where to begin all really have at this point is selecting all occurrences of the word namewith:

$test = "My name is Bob, her name is Sara."
$test -replace 'name', 'baby'
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...