Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove leading zeros from a string using regex

I am learning regex and java and working on a problem related to that.

I have an input string which can be any dollar amount like

$123,456.78
$0012,345.67
$123,04.56
$123,45.06

it also could be

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$0.1

I am trying to find if the dollar amount has leading zeros and trying to remove it.

so far I have tried this

string result = input_string.replaceAll(("[!^0]+)" , "");

But I guess I’m doing something wrong.
I just want to remove the leading zeros, not the ones between the amount part and not the one in cents. And if the amount is $0.1, I don’t want to remove it.

>Solution :

Match zeroes or commas that are preceded by a dollar sign and followed by a digit:

str = str.replaceAll("(?<=\\$)[0,]+(?=\\d)", "");

See live demo.

This covers the edge cases:

  • $001.23 -> $1.23
  • $000.12 -> $0.12
  • $00,123.45 -> $123.45
  • $0,000,000.12 -> $0.12

The regex:

  • (?<=\\$) means the preceding character is a dollar sign
  • (?=\\d) means the following character is a digit
  • [0,]+ means one or more zeroes or commas
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading