java正则表达式——判断字符串为哪种类型的数字?

时间:2022-08-09 18:49:08

在他人博客给出的代码基础上做了相应修改后,得到以下代码段来判断字符串是否为数字,为哪一类数字。

public class NumberValidation {

//匹配函数
private static boolean isMatch(String regex, String orginal){
if (orginal == null || orginal.trim().equals("")) {
return false;
}
Pattern pattern = Pattern.compile(regex);
Matcher isNum = pattern.matcher(orginal);
return isNum.matches();
}

//是否为正整数
public static boolean isPositiveInteger(String orginal) {
return isMatch("^\\+{0,1}[1-9]\\d*(\\,\\d{3})*", orginal);
}
//是否为负整数
public static boolean isNegativeInteger(String orginal) {
return isMatch("^-[1-9]\\d*(\\,\\d{3})*", orginal);
}
//是否为整数
public static boolean isWholeNumber(String orginal) {
return isMatch("[+-]{0,1}0", orginal) || isPositiveInteger(orginal) || isNegativeInteger(orginal);
}
//是否为正小数
public static boolean isPositiveDecimal(String orginal){
return isMatch("\\+{0,1}[0]\\.[1-9]*|\\+{0,1}[1-9]\\d*(\\,\\d{3})*\\.\\d*", orginal);
}
//是否为负小数
public static boolean isNegativeDecimal(String orginal){
return isMatch("^-[0]\\.\\d*|^-[1-9]\\d*(\\,\\d{3})*\\.\\d*", orginal);
}
//是否为小数
public static boolean isDecimal(String orginal){
return isMatch("[+-]{0,1}0{1}\\.0+", orginal) || isPositiveDecimal(orginal) || isNegativeDecimal(orginal);
//return isMatch("[-+]{0,1}\\d+\\.\\d*|[-+]{0,1}\\d*\\.\\d+", orginal);
}
//是否为实数
public static boolean isRealNumber(String orginal){
return isWholeNumber(orginal) || isDecimal(orginal);
}

//正则表达式判断,有bug:7-9会识别为true
public static boolean isNumeric(String orginal){
return isMatch("[+-]{0,1}[1-9][0-9]*.?[0-9]*|[+-]{0,1}[0].?[0-9]*", orginal);
}

/**
* @test
*/
public static void main(String args[]){
String ss="-0.999";

System.out.println("正整数:"+isPositiveInteger(ss));
System.out.println("负整数:"+isNegativeInteger(ss));
System.out.println("整数:"+isWholeNumber(ss));
System.out.println("正小数:"+isPositiveDecimal(ss));
System.out.println("负小数:"+isNegativeDecimal(ss));
System.out.println("小数:"+isDecimal(ss));
System.out.println("实数:"+isRealNumber(ss));
System.out.println("shuzi:"+isNumeric(ss));
}

}