繁体   English   中英

如何在字符串的开头创建用于删除所有“0”的正则表达式?

[英]How create regex for delete all `“0”` at the beginning of string?

如何删除字符串开头的所有"0"

00011 -> 11
00123 -> 123
000101 -> 101
101 -> 101
000002500 -> 2500

我试过了:

            Pattern pattern = Pattern.compile("([1-9]{1}[0-9]?+)");
            Matcher matcher = pattern.matcher("00049");
            matcher.matches();
            whatYouNeed = matcher.group();

我有错误: No match found

我试试

System.out.println("Status: " + "00012010003".replaceAll("^0+", ""));   

或仅限正则表达式:

yourString.replaceAll("^0+", "");

哪里

^ - matches only at start of string
0 - matches literal zeroes
+ - matches consecutive zeroes (at least one)

您应该将replaceAll^0*并替换为empty string而不是找到匹配项。

如果您的String仅包含问题中所述的数字。 你可以使用String.valueOf(Integer.parseInt("00011"))

你必须使用regex (?<=^)0+replaceFirst()
但是如果它是另一种形式,则在regex之前将你的值解析为string。

String val = "000011100";
String newVal = val.replaceFirst("(?<=^)0+", "");
System.out.println(newVal);

输出:

11100

在哪里?<=^是一个背后的外观。 正则表达式模式将仅与0匹配,即^后面的字符串开头。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM