判断字符串是不是数字–java 和js版

星期二, 2008-09-16 | Author: liyz | JAVA-and-J2EE | 6,798 views

今天有人问到,判断字符串是不是数字有什么方法,第一反应就是强制转换成Integer类型,若抛出异常就不是数字;
始终感觉不爽的方法;转念想可以用Pattern的方法,用正则表达式;问题解决了,不过还是想看看别人都是怎么解决的,网上查了下,还看了个用java类库自带的方法也还不错,不过要遍历;感觉还是用正则表达式的好;
把代码贴出来,下次用就直接复制了,呵呵

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.liyz.num.test;
 
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class TestNum {
	public static void main(String[] args) {
 
		boolean num=isNumeric("gg");
		System.out.println(num);
		boolean num2=isNum("25p");
		System.out.println(num2);
 
	}
 
	//jdk method java类库自带的方法
	public static boolean  isNum(String msg){
		char[] msgchar=msg.toCharArray();
		for(char mc:msgchar){
			if(!Character.isDigit(mc)){
				return false;
			}
		}
		return true;
		}
	// base on pattern 用正则表达式
	public static boolean isNumeric(String str)
	{
	Pattern pattern = Pattern.compile("[0-9]*");
	Matcher isNum = pattern.matcher(str);
	if( !isNum.matches() )
	{
	return false;
	}
	return true;
	}
}

——————————————————————————
差点忘记了还有个js版本,原理差不多,感觉更简单了,有现成的函数调用
貌似code标签不是很好用,只好换下了加了个–在script前

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<--script type="text/javascript">
    //系统函数的调用,感觉最简单
    if(isNaN("25")){
      alert("请输入数字");
    }
    //基于正则表达式的自己写的函数
    function isdigit(s)
   {
     var r,re;
           re = /\d*/;
           r = s.match(re);
           return (r==s)?true:false;
    }
     var s1 = "123";
     var s2 = "45a";
     var s3 = "bcd";
     var s4 = "e6"
   alert("s1="+isdigit(s1)+"s2="+isdigit(s2)+"s3="+isdigit(s3)+"s4="+isdigit(s4));
 
    <--/script>

Tags: , ,

文章作者: liyz

本文地址: https://www.pomelolee.com/22.html

除非注明,Pomelo Lee文章均为原创,转载请以链接形式标明本文地址

2 Comments to 判断字符串是不是数字–java 和js版

liyz
2009 年 02 月 25 日

今天用到数字匹配,发现还有好多正则表达式的,附上:
17种常用正则表达式
“^\\d+$” //非负整数(正整数 + 0)
“^[0-9]*[1-9][0-9]*$” //正整数
“^((-\\d+)|(0+))$” //非正整数(负整数 + 0)
“^-[0-9]*[1-9][0-9]*$” //负整数
“^-?\\d+$” //整数
“^\\d+(\\.\\d+)?$” //非负浮点数(正浮点数 + 0)
“^(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*))$” //正浮点数
“^((-\\d+(\\.\\d+)?)|(0+(\\.0+)?))$” //非正浮点数(负浮点数 + 0)
“^(-(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*)))$” //负浮点数
“^(-?\\d+)(\\.\\d+)?$” //浮点数
“^[A-Za-z]+$” //由26个英文字母组成的字符串
“^[A-Z]+$” //由26个英文字母的大写组成的字符串
“^[a-z]+$” //由26个英文字母的小写组成的字符串
“^[A-Za-z0-9]+$” //由数字和26个英文字母组成的字符串
“^\\w+$” //由数字、26个英文字母或者下划线组成的字符串
“^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$” //email地址
“^[a-zA-z]+://(\\w+(-\\w+)*)(\\.(\\w+(-\\w+)*))*(\\?\\S*)?$” //url

sara
2009 年 02 月 25 日

上面的两个方法都是检测正整数的,带小数点和带负数都不行,配合用正则表达式到是都能解决,jdk自带的就不行了只是int整数

Leave a comment

Search

文章分类

Links

Meta