在 Java 中,可以使用正则表达式来判断一个字符串是否是纯数字。以下是一个示例代码:

public class Main {
    public static void main(String[] args) {
        String str1 = '123456'; // 纯数字
        String str2 = 'abc123'; // 包含字母
        String str3 = '12.34'; // 包含小数点
        
        System.out.println(isNumeric(str1)); // true
        System.out.println(isNumeric(str2)); // false
        System.out.println(isNumeric(str3)); // false
    }
    
    public static boolean isNumeric(String str) {
        // 使用正则表达式匹配纯数字
        return str.matches('\d+');
    }
}

isNumeric方法中,使用matches方法和正则表达式\d+来判断字符串是否是纯数字。其中,\d表示匹配一个数字字符,+表示匹配一个或多个前面的元素。因此,如果字符串完全由数字字符组成,matches方法返回true,否则返回false

Java 判断字符串是否为纯数字:正则表达式方法

原文地址: https://www.cveoy.top/t/topic/hit5 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录