Marelons
Marelons

Reputation: 160

Regex to remove all zeroes except the last one

I'm building an expression that will be processing my fixed width files fields. I need to get rid of all the zeroes in front of the amount, but sometimes there is only zeroes in this field. There is always 11 characters in this field. This is the expression I have so far.

^0+(?=.$)

Works fine with 00000000000 as long as there are only zeroes in this field. However this is a payment app and this field stores amounts, so if we get for example 00000000099 it's not working as expected and returns whole string. What would be the best way to approach this? I'm still quite fresh to this, I must be missing a trivial thing. Thanks in advance.

Upvotes: 0

Views: 369

Answers (1)

JvdV
JvdV

Reputation: 75840

You haven't mentioned which app you are using. Maybe there is a function to remove padding? If you want regex, it looks like you could try:

^0+(?=\d+$)

And replace with nothing. See the online demo.

  • ^ - Start line anchor.
  • 0+ - Match 1+ zeros upto;
  • (?=\d+$) - A positive lookahead for 1+ digits before end line character.

Or use:

^0+(\d+)$

And replace by the 1st capture group. See the demo

  • ^ - Start line anchor.
  • 0+ - Match 1+ zeros upto;
  • (\d+) - 1st Capture group holding 1+ digits.
  • $ - End line anchor.

Upvotes: 2

Related Questions