Home > Software design >  Remove leading zeros from a string using regex
Remove leading zeros from a string using regex

Time:06-17

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

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

CodePudding user response:

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 zeros or commas

CodePudding user response:

You can use

string result = input_string.replaceFirst("(?<=\\$)0 (?=\\d)", "");

See the regex demo.

Details:

  • (?<=\$) - immediately on the left, there must be a $ char
  • 0 - one or more zeros
  • (?=\d) - immediately on the right, there must be any one digit.

CodePudding user response:

This is a simple regex that fits your needs:

str = str.replaceAll("^[$][,0] 0(?![.])", "$");
  • Related