![](/img/trans.png)
[英]Java regex - delete phrase from string if its not beginning of word
[英]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.