View Code
import java.util.regex.Pattern; public class NumberTest { /** * 正则表达式 * @param str * @return */ public static boolean isNumberic(String str){ Pattern pattern = Pattern.compile("[0-9]*"); return pattern.matcher(str).matches(); } /** * java自带函数 * @param str * @return */ public static boolean isNumberic2(String str){ for(int i = str.length();--i>=0;){ if(!Character.isDigit(str.charAt(i))){ return false; } } return true; } /** * 正则表达式 * @param str * @return */ public static boolean isNumberic3(String str){ if(str.matches("\\d*")){ return true; } return false; } /** * 判断ASCII * @param str * @return */ public static boolean isNumberic4(String str){ for(int i = str.length();--i>=0;){ int chr = str.charAt(i); if(chr < 48 || chr > 57){ return false; } } return true; } /** * 逐个判断str中的字符是否是0-9 * @param str * @return */ public static boolean isNumberic5(String str){ final String number = "0123456789"; for(int i = 0;i<str.length();i++){ if(number.indexOf(str.charAt(i)) == -1){ return false; } } return true; } public static void main(String[] args) { String str = "123"; boolean result1 = isNumberic(str); boolean result2 = isNumberic2(str); boolean result3 = isNumberic3(str); boolean result4 = isNumberic4(str); boolean result5 = isNumberic5(str); System.err.println(result1); System.err.println(result2); System.err.println(result3); System.err.println(result4); System.err.println(result5); } }