java8 判断字符串是否为纯数字
在Java 8中,可以使用正则表达式来判断一个字符串是否为纯数字。以下是一个示例代码:
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String str1 = "123456";
String str2 = "123abc";
if (isNumeric(str1)) {
System.out.println(str1 + " is numeric");
} else {
System.out.println(str1 + " is not numeric");
}
if (isNumeric(str2)) {
System.out.println(str2 + " is numeric");
} else {
System.out.println(str2 + " is not numeric");
}
}
public static boolean isNumeric(String str) {
Pattern pattern = Pattern.compile("-?\\d+(\\.\\d+)?");
return pattern.matcher(str).matches();
}
}
输出结果:
123456 is numeric
123abc is not numeric
在上面的代码中,我们使用Pattern类和正则表达式-?\\d+(\\.\\d+)?来判断一个字符串是否为纯数字。正则表达式-?\\d+(\\.\\d+)?表示一个可选的负号,后面跟着一串数字,可能包含小数点和小数部分。通过调用matcher(str).matches()方法,我们可以判断字符串是否与正则表达式匹配,如果匹配则返回true,否则返回false
原文地址: https://www.cveoy.top/t/topic/iNdl 著作权归作者所有。请勿转载和采集!