您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

java使用正则表达式判断传入数据是否为数字

2024/5/3 12:50:09发布22次查看
可以利用正则表达式来“-?[0-9]+(\\.[0-9]+)?”来做判断字符串是否为数字。
如果传入的数据有很多位,那么使用double会导致精度丢失,这个时候就要用bigdecimal来进行转换。
实例:
public class checkstrisnum { public static void main(string[] args) { double aa = -192322.1212; string a = "-192322.1212"; string b = "-192322a1212"; string c = "java"; string d = "5"; /** 判断是否全为数字 */ system.out.println(checkstrisnum02(double.tostring(aa))); system.out.println(checkstrisnum02(a)); system.out.println(checkstrisnum02(b)); system.out.println(checkstrisnum02(c)); system.out.println(checkstrisnum02(d)); } private static pattern number_pattern = pattern.compile("-?[0-9]+(\\.[0-9]+)?"); /** * 利用正则表达式来判断字符串是否为数字 */ public static boolean checkstrisnum02(string str) { string bigstr; try { /** 先将str转成bigdecimal,然后在转成string */ bigstr = new bigdecimal(str).tostring(); } catch (exception e) { /** 如果转换数字失败,说明该str并非全部为数字 */ return false; } matcher isnum = number_pattern.matcher(str); if (!isnum.matches()) { return false; } return true; } }
推荐教程:java开发入门
以上就是java使用正则表达式判断传入数据是否为数字的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product