How to use Java regex to determine if a string is a number?

You can use Java’s regular expressions to determine if a string is a number. Here is an example method implementation:

public static boolean isNumeric(String str) {
    // 使用正则表达式匹配数字
    String regex = "^[0-9]+$";
    return str.matches(regex);
}

In this example, the matches() method is used to check if the given string matches the specified regular expression. The regular expression “^[0-9]+$” means the string only contains numerical characters (0 to 9) and is not empty.

Here is an example of how it can be used:

public static void main(String[] args) {
    String str1 = "12345";
    String str2 = "12.34";
    
    System.out.println(isNumeric(str1)); // 输出:true
    System.out.println(isNumeric(str2)); // 输出:false
}

In the above examples, the isNumeric() method is used to check if two strings are numbers, with the output being true and false.

bannerAds