Java代码如何判断字符串中是不是都是数字呢?
下文笔者讲述使用Java代码检测字符串是不是都是数字的方法分享,如下所示
实现思路: 正则判断 或 借助Character.isDigit方法判断 或 char值码匹配 或 使用Long中的parse方法判断例
package com.java265.test2; import java.util.regex.Pattern; /** * Description: 检验数字字符 */ public class IsNumberDemo { public static void main(String[] args) { System.out.println("isNumber1:" + isNumber1("8293222525")); //true System.out.println("isNumber2:" + isNumber1("8293222525")); //true System.out.println("isNumber3:" + isNumber1("82932$22525")); //false System.out.println("isNumber4:" + isNumber1("82932#22525")); //false } //方法1 正则表达式 private static final Pattern MATCH_PATTERN = Pattern.compile("-?\\d+(\\.\\d+)?"); public static boolean isNumber1(String str) { return str != null && MATCH_PATTERN.matcher(str).matches(); } //方法2 Stream流(推荐) public static boolean isNumber2(String str) { return str != null && str.chars().allMatch(Character::isDigit); } //方法3 char码值匹配 public static boolean isNumber3(String str) { for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (c < 48 || c > 57) { return false; } } return true; } //方法4 使用Long封装类的parse方法 public static boolean isNumber4(String str) { try { Long.parseLong(str); return true; } catch(Exception e){ return false; } } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。