java 判断一个字符串是否是数字

梦里梦外; 2023-02-16 12:02 101阅读 0赞

一、用 java 自带的函数

  1. /**
  2. * 判断一个 string 类型的字符串是不是一个数字
  3. *
  4. * @param str string 类型的字符串
  5. * @return <code>true</code> 该 string 类型的字符串是十进制正整数. 其他的会返回<code>false</code>
  6. */
  7. private static boolean judgeByToCharArray(final String str) {
  8. // null or empty
  9. if (str == null || str.length() == 0) {
  10. return false;
  11. }
  12. return str.chars().allMatch(Character::isDigit);
  13. }

二、使用正则表达式

  1. /**
  2. * 使用正则表达式判断字符串是否是数字
  3. *
  4. * @param str string 类型的字符串
  5. * @return <code>true</code> 该 string 是整数. 其他的会返回<code>false</code>
  6. */
  7. public static boolean isNumericByRegEx(String str) {
  8. // ?:0或1个, *:0或多个, +:1或多个
  9. // 匹配所有整数
  10. Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
  11. // 匹配小数
  12. Pattern pattern2 = Pattern.compile("^[-\\+]?[\\d]+[.][\\d]+$");
  13. return pattern.matcher(str).matches() || pattern2.matcher(str).matches();
  14. }

三、使用 ascii 码

  1. /**
  2. * 使用 ASCII 码判断字符串是否是数字
  3. *
  4. * @param str string 类型的字符串
  5. * @return <code>true</code> 该 string 类型的字符串是十进制正整数. 其他的会返回<code>false</code>
  6. */
  7. public static boolean isNumericByAscii(String str) {
  8. if (str == null || str.length() == 0) {
  9. return false;
  10. }
  11. return str.chars().allMatch(chr -> (chr >= 48 && chr <= 57));
  12. }

四、parse 方法

  1. /**
  2. * 判断一个 string 类型的字符串是不是一个数字
  3. *
  4. * @param str string 类型的字符串
  5. * @return <code>true</code> 该 string 类型的字符串是十进制正整数. 其他的会返回<code>false</code>
  6. */
  7. public static boolean isNumeric(final String str) {
  8. // null or empty
  9. if (str == null || str.length() == 0) {
  10. return false;
  11. }
  12. try {
  13. Integer.parseInt(str);
  14. return true;
  15. } catch (NumberFormatException e) {
  16. try {
  17. Double.parseDouble(str);
  18. return true;
  19. } catch (NumberFormatException ex) {
  20. try {
  21. Float.parseFloat(str);
  22. return true;
  23. } catch (NumberFormatException exx) {
  24. return false;
  25. }
  26. }
  27. }
  28. }

五、第三方类库

  1. /**
  2. * 判断一个 string 类型的字符串是不是一个数字
  3. *
  4. * <p>
  5. * commons-lang3 库 -- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3
  6. * </p>
  7. *
  8. * @param str string 类型的字符串
  9. * @return <code>true</code> 该 string 类型的字符串是数字
  10. */
  11. private static boolean judgeByCommonsLong3(final String str) {
  12. // NumberUtils.isParsable(str)
  13. // NumberUtils.isDigits(str)
  14. // 这一个效果好一点
  15. return NumberUtils.isCreatable(str);
  16. }

发表评论

表情:
评论列表 (有 0 条评论,101人围观)

还没有评论,来说两句吧...

相关阅读