CRa
CRa

Reputation: 31

Powershell replace only numbers in beginning of string

I have a lot of strings that I am going to loop through and be changing various characters in. One thing I need to do is convert numbers at the beginning of the string to their string representation. Example: '10_hello_1' to 'ten_hello_1'. There will always be a '_' after a number. I have tried various things such as: $a.replace('\d{2}_','') (just to at least delete the beginning numbers) but that does not work.

I have even thought of breaking this down further and using a '$a.startswith()` clause but can not get powershell to ask "does this start with any arbitrary number".

I have found a lot about string manipulation on the web I just can't piece it altogether. Thanks!

Upvotes: 0

Views: 11430

Answers (2)

EBGreen
EBGreen

Reputation: 37730

The string .Replace method does not use regular expressions. Instead use the -Replace operator:

$a = '10_hello_1'
$a -replace '^\d+', ''

As for getting a word conversion of a number, I'm not aware of any built in method. Here is a question that proposes a .Net way to do it that you could easily convert to Powershell:

.NET convert number to string representation (1 to one, 2 to two, etc...)

Upvotes: 2

Matt
Matt

Reputation: 46710

EBGreen is perfectly correct as to why you are having an issue. I would like to offer a less error prone solution though.

$a -replace '^\d+_'

That would replace all numbers up to and including an underscore at the beginning of the string.

Upvotes: 2

Related Questions