Quantcast
Channel: PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources
Viewing all articles
Browse latest Browse all 8583

Replacing a particular character in a string with another character a specified number of times

$
0
0

Hello All

Here is a little trick I learned the other day which may be helpful to others (like any thing is PowerShell there is probably a dozen other ways to do the same thing, but this one is cool too)

Lets say you a have a string with a mix of letters and numbers but you do not know exactly the number of each or where appear in the string. Now you want to replace the first two numbers in the string with the # symbol

$String="ABB2Gt5yy45dd4t"
([regex]'\d').replace($String,'#',2)

the result of the above is

ABB#Gt#yy45dd4t

Now lets say you want to find the first set of two consecutive numbers and insert a # at the end of these two numbers and the next character (but not replace it)

([regex]'(?<=\d\d)').replace($String,'#',1)

the result of the above is

ABB2Gt5yy45#dd4t

of course there is a millions other things you can do

 

Hope someone else finds this particular method helpful

Ernie

 

 


Viewing all articles
Browse latest Browse all 8583

Trending Articles