r/PowerShell • u/ScubaFett • Jan 20 '26
Solved Replacing the nth instance of a character?
Is there a way to replace say the 3rd space in a string to a dash?:
The quick brown fox jumped over the lazy dog
becomes
The quick brown**-**fox jumped over the lazy dog
I'm doing this with file names so the words differ, otherwise I would do:$FileName = $FileName.Replace("brown fox","brown-fox")
Looking to avoid using split on space and then rejoining the text including the dash, or counting to the ~15th character etc. TIA
3
Upvotes
18
u/charleswj Jan 20 '26
Replace "2" with how many you want to ignore.
4
u/BlackV Jan 20 '26
I'd be using regex for this also, but.... Your examples is there always 3 or more spaces?
4
u/Trevski13 Jan 20 '26
Do a for loop through the string checking each character and count the spaces, on the third space swap it for a '-' and break
7
u/Relative_Test5911 Jan 20 '26
use a regex?
3
u/surfingoldelephant Jan 20 '26
Using a regex
MatchEvaluatoris another option. In PS v6+,-replaceaccepts a script block as the delegate.In Windows PowerShell v5.1,
Regex.Replace()needs to be used instead.And if you want to avoid hardcoding the space character, you can reference the matched value using
$_,$args[0]or a parameter (depending on the version).4
u/OlivTheFrog Jan 20 '26
HI,
There are diffrent ways to do this.
CharArrayExample of use
2) Use a regex (Found through a similar internet search. It's shorter, but not very understandable)
1
u/Thehoggle Jan 20 '26
Another method using regex replace, although other regex methods listed here are more efficient.
1
u/sodawillow Jan 28 '26
https://xkcd.com/208/ how could I forget to post this
0
u/jimb2 Jan 22 '26
Note: The unary split operator splits at whitespace blocks, not at each individual space, and ignores leading and trailing space. It's kinda robust - if that's what you want.
This code requires 4+ words.