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

当前回答

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

[1-9]\d+

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

其他回答

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

如果你(像我一样)需要从字符串中的每个“单词”中删除所有前导零,你可以修改@ polygeneluants的答案如下:

String s = "003 d0g 00ss 00 0 00";
s.replaceAll("\\b0+(?!\\b)", "");

结果是:

3 d0g ss 0 0 0

我认为这很容易做到。您可以从头开始循环字符串并删除零,直到找到一个非零字符。

int lastLeadZeroIndex = 0;
for (int i = 0; i < str.length(); i++) {
  char c = str.charAt(i);
  if (c == '0') {
    lastLeadZeroIndex = i;
  } else {
    break;
  }
}

str = str.subString(lastLeadZeroIndex+1, str.length());

使用Apache Commons StringUtils类:

StringUtils.strip(String str, String stripChars);

不使用Regex或substring()函数的字符串将是低效的-

public static String removeZero(String str){
        StringBuffer sb = new StringBuffer(str);
        while (sb.length()>1 && sb.charAt(0) == '0')
            sb.deleteCharAt(0);
        return sb.toString();  // return in String
    }