• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: Remove leading zeros from a string using regex

Resolved: Remove leading zeros from a string using regex

0
By Isaac Tonny on 17/06/2022 Issue
Share
Facebook Twitter LinkedIn

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
it also could be
I am trying to find if the dollar amount has leading zeros and trying to remove it.
so far I have tried this
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.

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!

java regex
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: Vaadin 14.9 – Redirect on Session Destroy Event

26/03/2023

Resolved: How to separate multiple answers in one column, for multiple columns, by creating extra columns

26/03/2023

Resolved: How to set consistent decimal separators in R data frame?

26/03/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.