Reputation: 23
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.
Upvotes: 1
Views: 3651
Reputation: 126732
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
Upvotes: 0
Reputation: 6657
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'
Upvotes: 2
Reputation: 60918
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)(?=.+)'
Upvotes: 2