如何从字母数字文本中删除前导零?

发布于 2024-09-01 14:35:47 字数 323 浏览 6 评论 0原文

我在 SO 中看到了有关如何在此处添加零前缀的问题。但不是相反!

你们能建议我如何删除字母数字文本中的前导零吗?是否有任何内置 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

I've seen questions on how to prefix zeros here in SO. But not the other way!

Can you guys suggest me how to remove the leading zeros in alphanumeric text? Are there any built-in APIs or do I need to write a method to trim the leading zeros?

Example:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(21

喜你已久 2024-09-08 14:35:47

正则表达式是完成这项工作的最佳工具;它应该是什么取决于问题的具体说明。下面的代码删除了前导零,但如果需要则保留 1(即它不会将 "0" 转换为空白字符串)。

s.replaceFirst("^0+(?!$)", "")

^ 锚点将确保匹配的 0+ 位于输入的开头。 (?!$) 负向先行确保不会匹配整个字符串。

测试工具:

String[] in = {
    "01234",         // "[1234]"
    "0001234a",      // "[1234a]"
    "101234",        // "[101234]"
    "000002829839",  // "[2829839]"
    "0",             // "[0]"
    "0000000",       // "[0]"
    "0000009",       // "[9]"
    "000000z",       // "[z]"
    "000000.z",      // "[.z]"
};
for (String s : in) {
    System.out.println("[" + s.replaceFirst("^0+(?!$)", "") + "]");
}

另请参阅

Regex is the best tool for the job; what it should be depends on the problem specification. The following removes leading zeroes, but leaves one if necessary (i.e. it wouldn't just turn "0" to a blank string).

s.replaceFirst("^0+(?!$)", "")

The ^ anchor will make sure that the 0+ being matched is at the beginning of the input. The (?!$) negative lookahead ensures that not the entire string will be matched.

Test harness:

String[] in = {
    "01234",         // "[1234]"
    "0001234a",      // "[1234a]"
    "101234",        // "[101234]"
    "000002829839",  // "[2829839]"
    "0",             // "[0]"
    "0000000",       // "[0]"
    "0000009",       // "[9]"
    "000000z",       // "[z]"
    "000000.z",      // "[.z]"
};
for (String s : in) {
    System.out.println("[" + s.replaceFirst("^0+(?!$)", "") + "]");
}

See also

苯莒 2024-09-08 14:35:47

您可以使用 StringUtils来自 Apache Commons Lang 的类,如下所示:

StringUtils.stripStart(yourString,"0");

You can use the StringUtils class from Apache Commons Lang like this:

StringUtils.stripStart(yourString,"0");
谢绝鈎搭 2024-09-08 14:35:47

如果您使用 Kotlin 这是您唯一需要的代码:

yourString.trimStart('0')

If you are using Kotlin This is the only code that you need:

yourString.trimStart('0')
不寐倦长更 2024-09-08 14:35:47

正则表达式方式怎么样:

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

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

如果像 Vadzim 一样,您对前导零的定义不包括将 "0" (或 "000" 或类似字符串)转换为空字符串(一个足够合理的字符串)期望),如有必要,只需将其放回去:

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

How about the regex way:

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

The ^ anchors to the start of the string (I'm assuming from context your strings are not multi-line here, otherwise you may need to look into \A for start of input rather than start of line). The 0* means zero or more 0 characters (you could use 0+ as well). The replaceFirst just replaces all those 0 characters at the start with nothing.

And if, like Vadzim, your definition of leading zeros doesn't include turning "0" (or "000" or similar strings) into an empty string (a rational enough expectation), simply put it back if necessary:

String s = "00000000";
s = s.replaceFirst ("^0*", "");
if (s.isEmpty()) s = "0";
苏佲洛 2024-09-08 14:35:47

一种清晰的方法,无需任何 regExp 和任何外部库。

public static String trimLeadingZeros(String source) {
    for (int i = 0; i < source.length(); ++i) {
        char c = source.charAt(i);
        if (c != '0') {
            return source.substring(i);
        }
    }
    return ""; // or return "0";
}

A clear way without any need of regExp and any external libraries.

public static String trimLeadingZeros(String source) {
    for (int i = 0; i < source.length(); ++i) {
        char c = source.charAt(i);
        if (c != '0') {
            return source.substring(i);
        }
    }
    return ""; // or return "0";
}
九公里浅绿 2024-09-08 14:35:47

要与thelost的Apache Commons答案相匹配:使用 guava-libraries (Google 的通用 Java我认为实用程序库现在应该位于任何重要 Java 项目的类路径上),这将使用 CharMatcher

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

To go with thelost's Apache Commons answer: using guava-libraries (Google's general-purpose Java utility library which I would argue should now be on the classpath of any non-trivial Java project), this would use CharMatcher:

CharMatcher.is('0').trimLeadingFrom(inputString);
七堇年 2024-09-08 14:35:47

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

You could just do:
String s = Integer.valueOf("0001007").toString();

朦胧时间 2024-09-08 14:35:47

使用这个:

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

Use this:

String x = "00123".replaceAll("^0*", ""); // -> 123
绿萝 2024-09-08 14:35:47

使用 Apache Commons <代码>StringUtils类:

StringUtils.strip(String str, String stripChars);

Use Apache Commons StringUtils class:

StringUtils.strip(String str, String stripChars);
自由如风 2024-09-08 14:35:47

将正则表达式与组一起使用:

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;

Using Regexp with groups:

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;
垂暮老矣 2024-09-08 14:35:47

正如一些答案所建议的那样,使用正则表达式是一个很好的方法。如果您不想使用正则表达式,则可以使用以下代码:

String s = "00a0a121";

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

Using regex as some of the answers suggest is a good way to do that. If you don't want to use regex then you can use this code:

String s = "00a0a121";

while(s.length()>0 && s.charAt(0)=='0')
{
   s = s.substring(1); 
}
惯饮孤独 2024-09-08 14:35:47

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

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

这会导致:

3 d0g ss 0 0 0

If you (like me) need to remove all the leading zeros from each "word" in a string, you can modify @polygenelubricants' answer to the following:

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

which results in:

3 d0g ss 0 0 0
关于从前 2024-09-08 14:35:47

使用 kotlin 很容易

value.trimStart('0')

Using kotlin it is easy

value.trimStart('0')
暗喜 2024-09-08 14:35:47

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

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());

I think that it is so easy to do that. You can just loop over the string from the start and removing zeros until you found a not zero char.

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());
回首观望 2024-09-08 14:35:47

如果不对 String 使用 Regexsubstring() 函数,这将是低效的 -

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
    }

Without using Regex or substring() function on String which will be inefficient -

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
    }
暗恋未遂 2024-09-08 14:35:47

您可以使用正则表达式将 "^0*(.*)" 替换为 "$1"

You could replace "^0*(.*)" to "$1" with regex

小伙你站住 2024-09-08 14:35:47
       String s="0000000000046457657772752256266542=56256010000085100000";      
    String removeString="";

    for(int i =0;i<s.length();i++){
      if(s.charAt(i)=='0')
        removeString=removeString+"0";
      else 
        break;
    }

    System.out.println("original string - "+s);

    System.out.println("after removing 0's -"+s.replaceFirst(removeString,""));
       String s="0000000000046457657772752256266542=56256010000085100000";      
    String removeString="";

    for(int i =0;i<s.length();i++){
      if(s.charAt(i)=='0')
        removeString=removeString+"0";
      else 
        break;
    }

    System.out.println("original string - "+s);

    System.out.println("after removing 0's -"+s.replaceFirst(removeString,""));
薄暮涼年 2024-09-08 14:35:47

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

If you don't want to use regex or external library.
You can do with "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
各空 2024-09-08 14:35:47

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

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

特别是正则表达式在长时间迭代中非常慢。 (我需要找到批处理作业的最快方法。)

I made some benchmark tests and found, that the fastest way (by far) is this solution:

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

Especially regular expressions are very slow in a long iteration. (I needed to find out the fastest way for a batchjob.)

客…行舟 2024-09-08 14:35:47

那么只搜索第一个非零字符怎么样?

[1-9]\d+

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

And what about just searching for the first non-zero character?

[1-9]\d+

This regex finds the first digit between 1 and 9 followed by any number of digits, so for "00012345" it returns "12345".
It can be easily adapted for alphanumeric strings.

乖乖哒 2024-09-08 14:35:47
  const removeFirstZero = (ele) => parseInt(ele).toString()
  
  console.log('raw ' + '0776211121')
  console.log('removedZero ' + removeFirstZero('0776211121'))

  const removeFirstZero = (ele) => parseInt(ele).toString()
  
  console.log('raw ' + '0776211121')
  console.log('removedZero ' + removeFirstZero('0776211121'))

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文