日期:2014-05-16  浏览次数:20381 次

java 或 jsp 中 判断一个字符串为数字

在编程过程中经常会遇到:要求传入的字符串只能为数字格式

记录集中简单的方法

1、java中? 使用类型转换判断

try {
???String str="sxy";
???int num=Integer.valueOf(str);//把字符串强制转换为数字
???return true;//如果是数字,返回True
??} catch (Exception e) {
??????????? return false;//如果抛出异常,返回False
??}

?

2、java中 使用正则表达式

String str = "sxy";
boolean isNum = str.matches("[0-9]+");
//+表示1个或多个,*表示0个或多个([0-9]*)(如""或"1"或"22"),?表示0个或1个([0-9]?)(如""或"7")

//true表示传入的是数字,false表示传入的含有非数字字符

?

3、java 中?? 使用Pattern类和Matcher

? String str = "sxy";
??Pattern pattern = Pattern.compile("[0-9]+");
??Matcher matcher = pattern.matcher((CharSequence) str);
??boolean result = matcher.matches();
??if (result) {
???System.out.println("true");
??} else {
???System.out.println("false");
??}

?

以上是java中的三种简单处理方式

下面说一下jsp中的方法:

1、jsp? 中 使用isNaN()函数

var str = "sxy123";

if(isNaN(str))
{
??? alert("输入了非数字字符!");?
}

?

2、jsp 中 使用正则表达式

var str="1234";

if( str.match("^[0-9]*$")){
alert("输入正确“)

?

?

?

?

?

?

?

?

?