1

Using Powershell, I'm trying to remove leading zeros of the numeric part of a string. Here are a couple of examples and expected results:

AB012 needs to become AB12

ABC010 needs to become ABC10

I've tried the following, but it gets rid of all zeros. How can I tell it to only remove the leading zeros? The format of the string will always be letters followed by numbers. However, the length of the letters may vary.

$x = ABC010
$y = $x -replace '[0]'
$y

This will display ABC1, and I wish to display ABC10.

Thanks.

3 Answers 3

2

This regex searches for a letter followed by any number of 0's and keeps the letter in the replacement pattern but strips the zeros:

$x = $x -replace '([a-z])0*', '$1'
Sign up to request clarification or add additional context in comments.

Comments

2

try this regex with look-behind and look-ahead assertions

'(?<=.+)(0)(?=.+)'

the problem is if you have string like "0AB0101" that become"0AB11" in this case use:

'(?<=\D)(0)(?=.+)'

Comments

0

Here's another option that evaluates the digits as a number:

PS> [regex]::replace('ABC010','(\d+)',{iex $args[0]})
ABC10 

Or using the TrimStart method:

PS> [regex]::replace('ABC010','(\d+)',{$args[0].ToString().TrimStart('0')})
ABC10

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.