去除数字字符串的前导0

假如有一些字符串里面保存的数字,但是为了某些目的需要将前导0给去掉,在Java里用什么办法最方便呢?

当然是正则替换啦。

 

 

public class StringTest {
	public static void main(String[] args) throws Exception {
		String[] tests = {"015633", "012", "0", "0000", "007000"};
		for(String s : tests) {
		  System.out.println(s.replaceAll("^0+(?!$)", ""));
		}
	}
}

 

 

 

 

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

其中^0+(?!$)这个正则表达式中的?!是否定前瞻,即此正则不匹配以0结尾的字符串最后的那个0

 

 

你可能感兴趣的:(Java)