0

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.

4
  • 3
    Use .replaceFirst("(?<=\\$)0+(?=\\d)", "") (demo) Commented Jun 16, 2022 at 21:40
  • Thanks @WiktorStribiżew, that worked with all requirements! :) Commented Jun 16, 2022 at 21:48
  • @adamn2 except it doesn't work for $0,012.34 Commented Jun 16, 2022 at 21:51
  • @WiktorStribiżew zeroes is not a typo Commented Jun 17, 2022 at 3:35

3 Answers 3

4

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

To handle any currency symbol:

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

See live demo.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use

string result = input_string.replaceFirst("(?<=\\p{Sc})[0,]+(?=\\d)", "");

See the regex demo.

Details:

  • (?<=\p{Sc}) - immediately on the left, there must be any currency char
  • [0,]+ - one or more zeros or commas
  • (?=\d) - immediately on the right, there must be any one digit.

Comments

0

This is a simple regex that fits your needs:

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

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.