Question:
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
so far I have tried this
Answer:
Match zeroes or commas that are preceded by a dollar sign and followed by a digit:str = str.replaceAll(“(?<=\\$)[0,]+(?=\\d)", ""); [/code]
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)", ""); [/code]
See live demo.If you have better answer, please add a comment about this, thank you!