Java判断字符串是否全是数字
下面展示一些 内联代码片
。
// package test;
import java.math.BigDecimal;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class test1 {
public static void main(String[] args) {
String a = "acbdw";
String b = "1269547";
String c = "AASIDK";
String d = "AIUydjs";
String e = "12sjaA";
String f = "3819247";
String g = "ausSHSzio";
String h = "IUFISsi`";
/** 判断是否全为数字 */
System.out.println(checkStrIsNum02(a));
System.out.println(checkStrIsNum02(b));
System.out.println(checkStrIsNum02(c));
System.out.println(checkStrIsNum02(d));
System.out.println(checkStrIsNum02(e));
System.out.println(checkStrIsNum02(f));
System.out.println(checkStrIsNum02(g));
System.out.println(checkStrIsNum02(h));
}
private static Pattern NUMBER_PATTERN = Pattern.compile("-?[0-9]+(\\.[0-9]+)?");
/**
* 利用正则表达式来判断字符串是否为数字
*/
public static boolean checkStrIsNum02(String str) {
String bigStr;
try {
/** 先将str转成BigDecimal,然后在转成String */
bigStr = new BigDecimal(str).toString();
} catch (Exception e) {
/** 如果转换数字失败,说明该str并非全部为数字 */
return false;
}
Matcher isNum = NUMBER_PATTERN.matcher(str);
if (!isNum.matches()) {
return false;
}
return true;
}
}
输出结果为