Java 如何从字母数字文本中删除前导零?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2800739/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove leading zeros from alphanumeric text?
提问by jai
I've seen questions on how to prefix zeros here in SO. But not the other way!
我已经看到有关如何在 SO 中添加零前缀的问题。但不是相反!
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?
你们能建议我如何删除字母数字文本中的前导零吗?是否有任何内置 API 或者我是否需要编写一种方法来修剪前导零?
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
采纳答案by polygenelubricants
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).
正则表达式是完成这项工作的最佳工具;它应该是什么取决于问题规范。以下删除前导零,但在必要时保留一个(即它不会只是变成"0"
一个空白字符串)。
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.
该^
主播将确保该0+
所匹配是在输入的开始。该(?!$)
负前瞻确保不是整个字符串匹配。
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
也可以看看
回答by YOU
You could replace "^0*(.*)"
to "$1"
with regex
你可以更换"^0*(.*)"
到"$1"
与正则表达式
回答by thelost
Use Apache Commons StringUtils
class:
使用 Apache CommonsStringUtils
类:
StringUtils.strip(String str, String stripChars);
回答by paxdiablo
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 coulduse 0+
as well). The replaceFirst
just replaces all those 0
characters at the start with nothing.
^
字符串开头的锚点(我从上下文假设您的字符串在这里不是多行的,否则您可能需要查看输入\A
的开头而不是行的开头)。这0*
意味着零个或多个0
字符(您也可以使用0+
)。在replaceFirst
刚刚替换所有那些0
在一开始什么也没有的字符。
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:
如果像 Vadzim 一样,您对前导零的定义不包括将"0"
(或"000"
类似字符串)转换为空字符串(足够合理的期望),只需在必要时将其放回原处:
String s = "00000000";
s = s.replaceFirst ("^0*", "");
if (s.isEmpty()) s = "0";
回答by vodkhang
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());
回答by Cowan
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:
要使用 thelost 的 Apache Commons 答案:使用guava-libraries(我认为 Google 的通用 Java 实用程序库现在应该在任何非平凡 Java 项目的类路径上),这将使用CharMatcher:
CharMatcher.is('0').trimLeadingFrom(inputString);
回答by magiccrafter
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";
}
回答by brj
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;
回答by Eduardo Cuomo
Use this:
用这个:
String x = "00123".replaceAll("^0*", ""); // -> 123
回答by Ajit Kumar Sahu
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,""));