我看到过关于如何在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

当前回答

如果你正在使用Kotlin,这是你唯一需要的代码:

yourString.trimStart('0')

其他回答

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

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

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

按照前面提到的Apache Commons的答案:使用guava-libraries(谷歌的通用Java实用程序库,我认为现在应该在任何非平凡Java项目的类路径上),这将使用CharMatcher:

CharMatcher.is('0').trimLeadingFrom(inputString);

使用regex作为一些答案建议是一个很好的方法。如果你不想使用regex,你可以使用下面的代码:

String s = "00a0a121";

while(s.length()>0 && s.charAt(0)=='0')
{
   s = s.substring(1); 
}

对组使用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;

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

[1-9]\d+

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