正则表达式:
判断一个字符串是不是都是数字,普通方法
public class Demo { public static void main(String[] args) { String str = "42a3432"; char[] chars = str.toCharArray(); boolean flag = true; int i = 0; for (; i < chars.length; i++) { if (chars[i]<'0'|chars[i]>'9'){ flag = false; break; } } if (flag){ System.out.println("全部都是数字"); } else{ System.out.println("第"+i+"个不是数字"); } } }
正则表示式
public class Demo { public static void main(String[] args) { String str = "423432"; Pattern compile = Pattern.compile("\d*"); Matcher m = compile.matcher(str); System.out.println(m.matches()); //开始真正的匹配 //字符串自带匹配正则 boolean matches = str.matches("\d*"); System.out.println(matches); } }
规则
^:起始符号,^x表示以x开头 $:结束符号,x$表示以x结尾 [n-m]:表示从n到m的数字 d:表示数字,等同于[0-9] X{m}:表示由m个X字符构成,d{4}表示4位数字
参考:https://www.runoob.com/regexp/regexp-syntax.html