Java中判断字符串是否为数字
转载:https://blog.csdn.net/u013066244/article/details/53197756
用JAVA自带的函数
public static boolean isNumericZidai(String str) {
for (int i = 0; i < str.length(); i++) {
System.out.println(str.charAt(i));
if (!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
其中Character.isDigit方法:确定或判断指定字符是否是一个数字。
测试方法:
public static void main(String[] args) {
double aa = -19162431.1254;
String a = "-19162431.1254";
String b = "-19162431a1254";
String c = "中文";
System.out.println(isNumericzidai(Double.toString(aa)));
System.out.println(isNumericzidai(a));
System.out.println(isNumericzidai(b));
System.out.println(isNumericzidai(c));
}
结果显示:
false
false
false
false
这种方法显然不能判断 负数。
用正则表达式
public static boolean isNumericzidai(String str) {
Pattern pattern = Pattern.compile("-?[0-9]+.?[0-9]+");
Matcher isNum = pattern.matcher(str);
if (!isNum.matches()) {
return false;
}
return true;
}
网上给出的最好的方法,可惜还是错误;首先正则表达式-?[0-9]+.?[0-9]+这里就错误
网上说:可匹配所有数字。
比如:
double aa = -19162431.1254;
String a = "-19162431.1254";
String b = "-19162431a1254";
String c = "中文";
System.out.println(isNumericzidai(Double.toString(aa)));
System.out.println(isNumericzidai(a));
System.out.println(isNumericzidai(b));
System.out.println(isNumericzidai(c));
结果
false
true
true
false
正确的正则表达式是:-?[0-9]+\\.?[0-9]*,点号.,是匹配任意字符,需要进行转义。
注意:感谢网友留言提示了一个错误,之前我的正则表达式是这么写的:
-?[0-9]+\\.?[0-9]+,这种正则表达式在匹配0-9的正负数时,会出错,这是因为该表达式最后是+,表示的是匹配前一个字符1次或无限次。
也就是说在匹配一位的时候,会出现错误。所以改为*,表示匹配前一位字符0次或无限次。
System.out.println(isNumeric("9"));
结果为
true
于是我们改成:
public static boolean isNumericzidai(String str) {
Pattern pattern = Pattern.compile("-?[0-9]+\\.?[0-9]*");
Matcher isNum = pattern.matcher(str);
if (!isNum.matches()) {
return false;
}
return true;
}
执行上面代码结果:
false
true
false
false
可是为什么double aa = -19162431.1254;没有匹配为true呢?
原来当数字位数很长时,系统会自动转为科学计数法。所以aa=-1.91624311254E7.
所以我们需要使用java专门用于商业精度计数的类 BigDecimal.
我们需要new BigDecimal(str),但是呢,如果str为中文,会报异常。所以我用try catch捕捉异常。
正确的通用代码(传入包含中文、负数、位数很长的数字的字符串也能正常匹配):
/**
* 匹配是否为数字
* @param str 可能为中文,也可能是-19162431.1254,不使用BigDecimal的话,变成-1.91624311254E7
* @return
* @author yutao
* @date 2016年11月14日下午7:41:22
*/
public static boolean isNumeric(String str) {
// 该正则表达式可以匹配所有的数字 包括负数
Pattern pattern = Pattern.compile("-?[0-9]+(\\.[0-9]+)?");
String bigStr;
try {
bigStr = new BigDecimal(str).toString();
} catch (Exception e) {
return false;//异常 说明包含非数字。
}
Matcher isNum = pattern.matcher(bigStr); // matcher是全匹配
if (!isNum.matches()) {
return false;
}
return true;
}
=====2018年2月5日======start===
评论中的新思路
public static boolean isNumeric(String str) {
String bigStr;
try {
bigStr = new BigDecimal(str).toString();
} catch (Exception e) {
return false;//异常 说明包含非数字。
}
return true;
}
如果是数字,创建new BigDecimal()时肯定不会报错,那就可以直接返回true啦!
=====2018年2月5日=====end====
======2018年3月5日=====start======
感谢评论中网友的纠错:
-?[0-9]+\\.?[0-9]*这个表达式在匹配字符串1.、222.时,确实会出现问题。
网友的建议改为:-?[0-9]+(\\.[0-9]+)?。
测试后,确实是可以的!
======2018年3月5日=====end======
使用org.apache.commons.lang
public static boolean isNumeric(String str)Checks if the String contains only unicode digits. A decimal point is not a unicode digit and returns false.
null will return false. An empty String ("") will return true.
StringUtils.isNumeric(null) = false
StringUtils.isNumeric("") = true
StringUtils.isNumeric(" ") = false
StringUtils.isNumeric("123") = true
StringUtils.isNumeric("12 3") = false
StringUtils.isNumeric("ab2c") = false
StringUtils.isNumeric("12-3") = false
StringUtils.isNumeric("12.3") = false
Parameters:
str - the String to check, may be null
Returns:
true if only contains digits, and is non-null
第三种我没有测试,网上说,也不能判断负数。
又因为使用第三方的包,我懒得用,java原生就很好了。
====2018年3月5日=====
今天测试了org.apache.commons.lang3.StringUtils中的isNumeric,依旧不能判断负数、带小数点的数字。
对于第三方org.apache.commons.lang3包,是个好东西,但是也有很多bug的,用的时候多测测。
总结
肯定是使用第二种正则表达式计算啦!正则表达式用对地方啦,就不慢!
动不动就说正则太慢的人,是玩不6正则表达式的!
=====2018年2月5日======
可以不使用正则,直接通过是否有异常来判断 —— 评论中网友给出的答案!
感觉可行(因为没有实战过,只是简单的测试了下!)
======2018年3月5日=====start======
感谢网友提的建议,可以看出,我的测试用例没有弄好;
如果依然要使用正则表达式的话,目前正确的是:-?[0-9]+(\\.[0-9]+)?。
---------------------
Java中判断字符串是否为数字的更多相关文章
- (转载)java中判断字符串是否为数字的方法的几种方法
java中判断字符串是否为数字的方法: 1.用JAVA自带的函数 public static boolean isNumeric(String str){ for (int i = 0; i < ...
- 字符串--java中判断字符串是否为数字的方法的几种方法?
ava中判断字符串是否为数字的方法: 1.用JAVA自带的函数 public static boolean isNumeric(String str){ for (int i = 0; i < ...
- java中判断字符串是否为数字的方法的几种方法
1.用JAVA自带的函数 public static boolean isNumeric(String str){ for (int i = 0; i < str.length(); i++){ ...
- Java中判断字符串是否为数字的五种方法
//方法一:用JAVA自带的函数 public static boolean isNumeric(String str){ for (int i = str.length();--i>=0;){ ...
- Java中判断字符串是否为数字的五种方法 (转)
推荐使用第二个方法,速度最快. 方法一:用JAVA自带的函数 public static boolean isNumeric(String str){ for (int i = str.length( ...
- 【工具类】Java中判断字符串是否为数字的五种方法
1 //方法一:用JAVA自带的函数 2 public static boolean isNumeric(String str){ 3 for (int i = str.length();--i> ...
- java中判断字符串是否为数字的方法
一: //1.用JAVA自带的函数 public static boolean isNumeric(String str){ for (int i = 0; i < str.length(); ...
- java中判断字符串是否为数字的三种方法
以下内容引自 http://www.blogjava.net/Javaphua/archive/2007/06/05/122131.html 1用JAVA自带的函数 public static ...
- [转]java中判断字符串是否为数字的三种方法
1用JAVA自带的函数public static boolean isNumeric(String str){ for (int i = str.length();--i>=0;){ ...
随机推荐
- AOP+Token防止表单重复提交
表单重复提交: 由于用户误操作,多次点击表单提交按钮 由于网速等原因造成页面卡顿,用户重复刷新提交页面 避免表单重复提交的方式: 1.页面上的按钮做防重复点击操作 2.在数据库中可以做唯一约束 3.利 ...
- ByteBuffer常见方法
ByteBuffer的三个属性 limit:所有对Buffer读写操作都会以limit变量的值作为上限. position:代表对缓冲区进行读写时,当前游标的位置. capacity:代表缓冲区的最大 ...
- 作为一个纯粹数据结构的 Redis Streams
来源:antirez 翻译:Kevin (公众号:中间件小哥) Redis 5 中引入了一个名为 Streams 的新的 Redis 数据结构,吸引了社区极大的兴趣.接下来,我会在社区里进行调查,同用 ...
- yum安装k8s集群
k8s的安装有多种方式,如yum安装,kubeadm安装,二进制安装等.本文是入门系列,只是为了快速了解k8s的原理和工作过程,对k8s有一个快速的了解,这里直接采用yum安装 的1.5.2为案例进行 ...
- 使用lxml解析HTML代码
做个参考,转自:https://blog.csdn.net/qq_42281053/article/details/80658018
- 接口标记为@ResponseBody却不进入ResponseBodyAdvice
一.背景: 我们的接口为了统一,在ResponseBodyAdvice中对返回值做统一处理,默认添加了errorNo和errorInfo字段返回. 最近同事改接口代码的时候,发现接口返回值是空的.乍一 ...
- C# vb .net实现移除透明度效果
在.net中,如何简单快捷地实现Photoshop滤镜组中的移除透明度效果呢?答案是调用SharpImage!专业图像特效滤镜和合成类库.下面开始演示关键代码,您也可以在文末下载全部源码: 设置授权 ...
- leetcode 数组
寻找数组的中心索引 给定一个整数类型的数组 nums,请编写一个能够返回数组"中心索引"的方法. 我们是这样定义数组中心索引的:数组中心索引的左侧所有元素相加的和等于右侧所有元素相 ...
- python 简单工厂模式
abc 是抽象类模块abc.ABC 是继承抽象类 也可直接继承 (metaclass=ABCMeta)abc.abstractmethod 是定义抽象方法 简单工厂模式:通过接口创建对象,但不会暴露 ...
- 将h5用HBuilderX打包成安卓app后,document.documentElement.scrollTop的值始终为0或者document.body.scrollTop始终为0
let time = setInterval(() => { let scroll = document.documentElement.scrollTop || document.body.s ...