java 中,如何判断字符串是否是整数呢?
有两种方式:
方式一:通过正则表达式
/***
* 判断 String 是否int
*
* @param input
* @return
*/
public static boolean isInteger(String input){
Matcher mer = Pattern.compile("^[0-9]+$").matcher(input);
return mer.find();
}
上述方法不完善,不能识别负数,比如识别不了“-9”,“+9”。多谢大家指教,改进如下:
/***
* 判断 String 是否是 int
*
* @param input
* @return
*/
public static boolean isInteger(String input){
Matcher mer = Pattern.compile("^[+-]?[0-9]+$").matcher(input);
return mer.find();
}
测试代码如下:
@Test
public void test_isInteger(){
String input="123";
System.out.println(input+":"+ValueWidget.isInteger(input) );
input="000000000000009";
System.out.println(input+":"+ValueWidget.isInteger(input) );
input="-9";
System.out.println(input+":"+ValueWidget.isInteger(input) );
input="-09";
System.out.println(input+":"+ValueWidget.isInteger(input) );
input="--9";
System.out.println(input+":"+ValueWidget.isInteger(input) );
}
运行结果:
123:true
000000000000009:true
-9:true
-09:true
--9:false
方式二:通过java 的异常
public static boolean isValidInt(String value) {
try {
Integer.parseInt(value);
} catch (NumberFormatException e) {
return false;
}
return true;
}