新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

java正则判断数字怎么实现,java正则表达式判断数字

发布时间:2023-11-04 16:11:29

java正则判断数字怎样实现

可使用正则表达式来判断一个字符串是否是为数字。以下是一个使用正则表达式判断数字的示例代码:

import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        String str1 = "12345";
        String str2 = "12.345";
        String str3 = "⑴23";
        String str4 = "abc123";

        System.out.println(isNumeric(str1)); // 输出: true
        System.out.println(isNumeric(str2)); // 输出: true
        System.out.println(isNumeric(str3)); // 输出: true
        System.out.println(isNumeric(str4)); // 输出: false
    }

    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("-?\d+(\.\d+)?");
        return pattern.matcher(str).matches();
    }
}

上述代码中,isNumeric方法使用了正则表达式-?\d+(\.\d+)?来判断字符串是否是为数字。该正则表达式的含义是:可选的负号,后面随着一个或多个数字(整数部份),然后可选的小数部份由一个小数点和一个或多个数字组成。

通过调用pattern.matcher(str).matches()方法来判断字符串是否是匹配该正则表达式,如果匹配则返回true,否则返回false