Java 正则表达式去除被视为字符串的前导零
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29658654/
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
regex to strip leading zeros treated as string
提问by Horse Voice
I have numbers like this that need leading zero's removed.
我有这样的数字需要删除前导零。
Here is what I need:
这是我需要的:
00000004334300343
-> 4334300343
00000004334300343
-> 4334300343
0003030435243
-> 3030435243
0003030435243
-> 3030435243
I can't figure this out as I'm new to regular expressions. This does not work:
我无法弄清楚这一点,因为我是正则表达式的新手。这不起作用:
(^0)
采纳答案by Rohit Jain
You're almost there. You just need quantifier:
您快到了。你只需要量词:
str = str.replaceAll("^0+", "");
It replaces 1 or more occurrences of 0 (that is what +
quantifier is for. Similarly, we have *
quantifier, which means 0 or more), at the beginning of the string (that's given by caret - ^
), with empty string.
它用空字符串替换 1 次或多次出现的 0(这就是+
量词的用途。类似地,我们有*
量词,表示 0 或更多),在字符串的开头(由插入符号 - 给出^
)。
回答by anubhava
回答by SubOptimal
回答by MaxZoom
The correct regex to strip leading zeros is
去除前导零的正确正则表达式是
str = str.replaceAll("^0+", "");
This regex will match 0
character in quantity of one and more
at the string beginning.
There is not reason to worry about replaceAll
method, as regex has ^
(begin input) special character that assure the replacement will be invoked only once.
此正则表达式将匹配字符串开头的0
字符数量one and more
。没有理由担心replaceAll
方法,因为正则表达式具有^
(开始输入)特殊字符,可确保仅调用一次替换。
Ultimatelyyou can use Java build-in feature to do the same:
最终,您可以使用 Java 内置功能来执行相同的操作:
String str = "00000004334300343";
long number = Long.parseLong(str);
// outputs 4334300343
The leading zeros will be stripped for you automatically.
将自动为您去除前导零。
回答by Luis Colorado
回答by Artur Dumchev
Accepted solution will fail if you need to get "0" from "00". This is right one:
如果您需要从“00”获取“0”,则已接受的解决方案将失败。这是对的:
str = str.replaceAll("0+(?!$)", "");
"^0+(?!$)" means match one or more zeros if it is not followed by end of string.
"^0+(?!$)" 表示匹配一个或多个零,如果后面没有跟字符串结尾。