regex to strip leading zeros treated as string

后端 未结 6 1313
灰色年华
灰色年华 2020-12-30 04:28

I have numbers like this that need leading zero\'s removed.

Here is what I need:

00000004334300343 -> 4334300343

000

6条回答
  •  感动是毒
    2020-12-30 04:54

    The correct regex to strip leading zeros is

    str = str.replaceAll("^0+", "");
    

    This regex will match 0 character in quantity of one and more at the string beginning. There is not reason to worry about replaceAll method, as regex has ^ (begin input) special character that assure the replacement will be invoked only once.

    Ultimately you can use Java build-in feature to do the same:

    String str = "00000004334300343";
    long number = Long.parseLong(str);
    // outputs 4334300343
    

    The leading zeros will be stripped for you automatically.

提交回复
热议问题