判断一个字符是否为数字0-9
【1】调用Character方法 isDigit()
public boolean isNum(char ch){
if(Character.isDigit(ch))
return true;
else
return false;
}
【2】正则表达式
public boolean isNum(char ch){
String str_ch=String.valueOf(ch);
Pattern pattern = Pattern.compile("\\d");
Matcher isNum = pattern.matcher(str_ch); // matcher是全匹配
if (!isNum.matches())
return false;
else
return true;
判断一个字符串是否为数字型(包括正负整数、正负小数)
/*两种正则式的写法是等价的*/
public static boolean isNum(String str) {
//Pattern pattern = Pattern.compile("-?[0-9]+(\\.[0-9]+)?");
Pattern pattern = Pattern.compile("-?\\d+(\\.\\d+)?");
Matcher isNum = pattern.matcher(str);
if (!isNum.matches())
return false;
else
return true;
}
测试集:
{ 12 ,12. , 12.3 ,12.34 、12.34.56 、 -12 、-12.34 }
测试结果:
true,false,true,true,false,true,true