简体   繁体   中英

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

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?

You can use the replaceFirst method of String which takes a regex as its first argument to archieve that.

eg:

System.out.println("00002021".replaceFirst("0+", ""));

will print

2021

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM