java正则表达式matcher,find的注意

正则很经常用,最近在开发碰到一些问题,提醒大家注意下。

 

一个字符串,要判断是否是数字,可以0为头

 

正确的做法:

Pattern intPattern = Pattern.compile("[0-9]+");
Matcher m = intPattern.matcher("aaa010222");
System.out.print(m.matches());

  

 返回false,因为m.matches()是整串匹配,如果是 0102222,则返回true

 

 

错误做法:

Pattern intPattern = Pattern.compile("[0-9]+");
Matcher m = intPattern.matcher("aaaa10222");
System.out.print(m.find());

 

返回true,m.find() 会找某部分如果匹配就为完成,因此适合查找某部分符合特征。

 

 

 

你可能感兴趣的:(java,正则表达式)