5

I am using this to remove leading zeros from my input string.

return a.replaceAll("^0+",""); 

But the above string even removes from any string which is alphanumeric as well. I do not want to do that. My requirement is:

Only the leading zeros of numeric numbers should be removed e.g.

00002827393 -> 2827393

If you have a alpha numeric number the leading zeros must not be removed e.g.

000ZZ12340 -> 000ZZ12340
4

5 回答 5

10

您可以先检查您的字符串是否仅由数字组成:

Pattern p = Pattern.compile("^\\d+$");
Matcher m = p.matcher(a);

if(m.matches()){
  return a.replaceAll("^0+", "");
} else {
  return a;
}

还 :

  • 考虑让你的模式静态,这样它只会被创建一次
  • 您可能希望在较小的函数中使用匹配器隔离部分,例如“isOnlyDigit”
于 2013-04-08T22:12:03.187 回答
7

你也可以试试这个:

a.replaceAll("^0+(?=\\d+$)", "")

请注意,正向先行(?=\\d+$)检查字符串的其余部分(在起始0s 之后,由 匹配^0+)在匹配/替换任何内容之前仅由数字组成。


System.out.println("00002827393".replaceAll("^0+(?=\\d+$)", ""));
System.out.println("000ZZ12340".replaceAll("^0+(?=\\d+$)", ""));
2827393
000ZZ12340
于 2013-04-08T22:19:26.543 回答
4

测试传入的字符串是否与数字模式“\d+”匹配。"\d" 是数字的字符类。如果是数字,则返回调用结果replaceAll,否则只返回原始字符串。

if (str.matches("\\d+"))
    return str.replaceAll("^0+", "");
return str;

测试:

public static void main (String[] args) throws java.lang.Exception
{
   System.out.println(replaceNumZeroes("0002827393"));
   System.out.println(replaceNumZeroes("000ZZ1234566"));
}

产生输出

2827393
000ZZ1234566
于 2013-04-08T22:11:23.797 回答
0

逻辑:它将字符串转换为 char 数组并从 i=0 开始;一旦它击中第一个数字值,它就会从 for 循环中中断,并且一旦它击中第一个字符(除了 1 到 9),它就会返回相同的字符串。在第一个 for 循环之后,我们需要考虑以下情况:

case 1. 00000000000
case 2. 00000011111
case 3. 11111111111

如果它是 1 或 3(即第一个 for 循环中的 i 值将是 0 或字符串的长度),那么只需返回字符串。否则,对于第二种情况,从 char 数组复制到一个新的 char 数组,该数组以 i 的值开始(我们将从第一个 for 循环中获得 i 的值,它保存第一个数值位置。)。希望它清除。 在此处输入图像描述

    public String trimLeadingZeros(String str)
    {
    if (str == null)
    {
        return null; //if null return null
    }
    char[] c = str.toCharArray();
    int i = 0;

    for(; i<c.length; i++)
    {
        if(c[i]=='0')
        {
           continue; 
        }
        else if(c[i]>='1' && c[i]<='9')
        {
            break;
        }
        else
        {
            return str;
        }
    }
    if(i==0 || i==c.length)
    {
        return str;
    }
    else
    {
        char[] temp = new char[c.length-i];
        int index = 0;
        for(int j=i; j<c.length; j++)
        {
            temp[index++] = c[j];
        }
        return new String(temp);
    }
    }
于 2013-04-08T22:57:59.320 回答
0

只是我做了以下

String string = string.trim();
while(string.charAt(0) == '0'){
    string = string.substring(1);
}
于 2014-06-18T07:01:15.610 回答