Home  >  Article  >  Java  >  How to check if a string contains only numbers in Java?

How to check if a string contains only numbers in Java?

王林
王林forward
2023-04-20 19:22:062104browse

如何检查字符串中只包含数字

有一种很傻的解法,就是用 Long.parseLong(string) 对字符串强转,如果转不成整形,那肯定不是只包含数字,对吧?

但这种方法也太不可取了,所以还得换一种巧妙的,就是使用正则表达式。

public class CheckIfStringContainsDigitsOnly {     public static void main(String[] args) {         digitsOnlyString("123 沉默王二");         digitsOnlyString("123");      }      private static void digitsOnlyString(String string) {         if (string.matches("\\d+")) {             System.out.println("只包含数字的字符串:" + string);         }     } }

输出结果如下所示:

只包含数字:123

The above is the detailed content of How to check if a string contains only numbers in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete