regex to strip leading zeros treated as string

后端 未结 6 1270
灰色年华
灰色年华 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:52

    You're almost there. You just need quantifier:

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

    It replaces 1 or more occurrences of 0 (that is what + quantifier is for. Similarly, we have * quantifier, which means 0 or more), at the beginning of the string (that's given by caret - ^), with empty string.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-30 04:57

    \b0+\B will do the work. See demo \b anchors your match to a word boundary, it matches a sequence of one or more zeros 0+, and finishes not in a word boundary (to not eliminate the last 0 in case you have only 00...000)

    0 讨论(0)
  • 2020-12-30 05:06

    Another solution (might be more intuitive to read)

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

    ^ - match the beginning of a line
    0+ - match the zero digit character one or more times

    A exhausting list of pattern you can find here Pattern.

    0 讨论(0)
  • 2020-12-30 05:07

    Accepted solution will fail if you need to get "0" from "00". This is right one:

    str = str.replaceAll("0+(?!$)", "");
    

    "^0+(?!$)" means match one or more zeros if it is not followed by end of string.

    0 讨论(0)
  • 2020-12-30 05:17

    If you know input strings are all containing digits then you can do:

    String s = "00000004334300343";
    System.out.println(Long.valueOf(s));
    // 4334300343
    

    Code Demo

    By converting to Long it will automatically strip off all leading zeroes.

    0 讨论(0)
提交回复
热议问题