Home > front end >  Remove Character Occurrences Until the First Different One, Java
Remove Character Occurrences Until the First Different One, Java

Time:12-07

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

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?

CodePudding user response:

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

  • Related