0

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!

CRa
  • 31
  • 1
  • 1
  • 5
  • 1
    What is exact thing you want to help with? Writing function to convert from number to text? Checking if string starts with digits, and replacing that digits? – user4003407 Jul 09 '15 at 18:11
  • checking if a string starts with digits and replacing digits. The digits could be any number of characters long followed by a '_' character – CRa Jul 09 '15 at 18:14

2 Answers2

2

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...)

Community
  • 1
  • 1
EBGreen
  • 36,735
  • 12
  • 65
  • 85
  • Oh... Is there a general way to identify what does and does not work with regular expressions? – CRa Jul 09 '15 at 18:23
  • I don't know of any way off the top of my head. I just look at the documentation. – EBGreen Jul 09 '15 at 18:24
  • Edited to cause the regex to replace all starting numerals rather than just the two digits asked for in the question. – EBGreen Jul 09 '15 at 18:47
2

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.

Matt
  • 45,022
  • 8
  • 78
  • 119