java中判断字符串是否为纯数字

如题所述

第1个回答  2015-10-03
方法一:利用正则表达式
public class Testone {
public static void main(String[] args){
String str="123456";
boolean result=str.matches("[0-9]+");
if (result == true) {
System.out.println("该字符串是纯数字");
}else{
System.out.println("该字符串不是纯数字");
}
}
}
方法二:利用Pattern.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Testone {
public static void main(String[] args){
String str="123456";
Pattern pattern = Pattern.compile("[0-9]{1,}");
Matcher matcher = pattern.matcher((CharSequence)str);
boolean result=matcher.matches();
if (result == true) {
System.out.println("该字符串是纯数字");
}else{
System.out.println("该字符串不是纯数字");
}
}
}
第2个回答  2018-07-19
纯数字判断不需要自己写正则
直接用apache工具包的方法StringUtils.isNumeric(str),但是这个方法只能判断纯数字,带有+,-,. 的字符串返回都是false
相似回答