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 Character Occurrences Until the First Different One, Java

So I have some numerical strings like the following ones:

"00000545468" – "00002021" – "000000001990" etc.. (I don’t know how this strings will be passed to me, the only thing I know is that they will start with some zeros from left and then there will be other different numbers)

I want to remove all the zeros (0) occurrences from left until the first different number of the string.
So if I have for example "00002021", I want to have as a result "2021" and if I have "000000001990" I want "1990".

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

I excluded the usage of .replace("0", ""), because by doing this I would also remove the zero in "2021" and in "1990", and I don’t want this to happen.

Any suggestions?

>Solution :

You can use replaceFirst or replaceAll but the main point is to anchor your regex so it will only replace the zeroes if they are placed at the begining of the string.

"00002021".replaceFirst("^0+", "")

should return what you need, and does not replace zeroes if they are not at the beginning of the string.

You can check this at https://www.regexplanet.com/advanced/java/index.html (disclaimer: I do not own this website and I do not profit by linking to it).

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