- 使用正则表达式
public boolean isNumeric(String str){
Pattern pattern = Pattern.compile("[0-9]*");
Matcher isNum = pattern.matcher(str);
if( !isNum.matches() ){
return false;
}
return true;
}
- 使用org.apache.commons.lang
boolean result = StringUtils.isNumeric("a123");
- 捕获NumberFormatException异常
public static boolean isNumeric(String str)
{
try{
Integer.parseInt(str);
return true;
}catch(NumberFormatException e){
return false;
}
}
- 使用Character.isDigit()
public static boolean isNumeric(String str) {
for (int i = 0; i < str.length(); i++) {
if (!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
原文链接:https://www.cnblogs.com/guop/p/5216836.html