java正则验证是否是数字的逻辑问题
######代码如下:
public static boolean isNumber(String str){
if(str == null || "".equals(str)){
return false;
}
Pattern pattern = Pattern.compile("^-?(([1-9]+[0-9]?)|[0]){1}(.[0-9]*[1-9])?$");
return pattern.matcher(str).matches();
}
测试代码及结果如下:
@Test
public void isNumber() {
int i = 1;
System.out.println(1 + " " + NumberUtils.isNumber("-123"));
System.out.println(2 + " " + NumberUtils.isNumber("120"));
System.out.println(3 + " " + NumberUtils.isNumber("012"));
System.out.println(4 + " " + NumberUtils.isNumber("0"));
System.out.println(5 + " " + NumberUtils.isNumber("-1.23"));
System.out.println(6 + " " + NumberUtils.isNumber("1.23"));
System.out.println(7 + " " + NumberUtils.isNumber("-0.23"));
System.out.println(8 + " " + NumberUtils.isNumber("-12.3"));
System.out.println(9 + " " + NumberUtils.isNumber("-123."));
System.out.println(10 + " " + NumberUtils.isNumber("-123.12"));
System.out.println(11 + " " + NumberUtils.isNumber("-123.12240"));
System.out.println(12 + " " + NumberUtils.isNumber("-123.0"));
System.out.println(13 + " " + NumberUtils.isNumber("-0.0"));
System.out.println(14 + " " + NumberUtils.isNumber("01.01"));
System.out.println(15 + " " + NumberUtils.isNumber("0120"));
}
测试运行结果:
1 true
2 true
3 true
4 true
5 true
6 true
7 true
8 true
9 false
10 true
11 false
12 false
13 false
14 false
15 false
其他都是对的,但第3条有问题,和预想的不符合。且第3条与第15条差别仅在于后边多了个0,结果却不同。有精通正则表达式的大佬帮忙解惑吗