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

当前回答

用这个:

String x = "00123".replaceAll("^0*", ""); // -> 123

其他回答

那么regex的方法呢:

String s = "001234-a";
s = s.replaceFirst ("^0*", "");

^锚定到字符串的开始(我假设从上下文你的字符串不是多行这里,否则你可能需要查看\A的输入开始而不是行开始)。0*表示0个或多个0字符(也可以使用0+)。replaceFirst只是将开始的所有0字符替换为空。

如果像Vadzim一样,你对前导零的定义不包括将“0”(或“000”或类似的字符串)转换为空字符串(一个足够合理的期望),那么在必要时简单地将它放回去:

String s = "00000000";
s = s.replaceFirst ("^0*", "");
if (s.isEmpty()) s = "0";

如果您不想使用正则表达式或外部库。 你可以用“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

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

用这个:

String x = "00123".replaceAll("^0*", ""); // -> 123

你可以这样做: String s = Integer.valueOf("0001007").toString();