我看到过关于如何在SO中加上0前缀的问题。但不是相反!

你们能建议我如何去掉字母数字文本中的前导零吗?是否有任何内置api,或者我需要写一个方法来修剪前导零?

例子:

01234 converts to 1234
0001234a converts to 1234a
001234-a converts to 1234-a
101234 remains as 101234
2509398 remains as 2509398
123z remains as 123z
000002829839 converts to 2829839

当前回答

如果您不想使用正则表达式或外部库。 你可以用“for”:

String input="0000008008451"
String output = input.trim();
for( ;output.length() > 1 && output.charAt(0) == '0'; output = output.substring(1));

System.out.println(output);//8008451

其他回答

我做了一些基准测试,发现(到目前为止)最快的方法是这个解决方案:

    private static String removeLeadingZeros(String s) {
      try {
          Integer intVal = Integer.parseInt(s);
          s = intVal.toString();
      } catch (Exception ex) {
          // whatever
      }
      return s;
    }

特别是正则表达式在长时间迭代中非常缓慢。(我需要找出批量生产最快的方法。)

你可以像这样使用Apache Commons Lang中的StringUtils类:

StringUtils.stripStart(yourString,"0");

对组使用Regexp:

Pattern pattern = Pattern.compile("(0*)(.*)");
String result = "";
Matcher matcher = pattern.matcher(content);
if (matcher.matches())
{
      // first group contains 0, second group the remaining characters
      // 000abcd - > 000, abcd
      result = matcher.group(2);
}

return result;

使用Apache Commons StringUtils类:

StringUtils.strip(String str, String stripChars);

如果只搜索第一个非零字符呢?

[1-9]\d+

这个正则表达式查找1到9之间的第一个数字,后面跟着任意数量的数字,因此对于“00012345”,它返回“12345”。 它可以很容易地适应字母数字字符串。