正则表达式(二)
public static void main(String[] args) { String str1,str2,str3,pattern; str1="fa"; str2="f2"; pattern="[a-z][0-9]";//匹配的格式两个字符,第一个字符范围是小写字母a-z,第二个范围是数字0-9 Pattern r=Pattern.compile(pattern); Matcher m1=r.matcher(str1); Matcher m2=r.matcher(str2); System.out.println(m1.matches());//false System.out.println(m2.matches());//true //=============================================== str1="中1"; str2="1中"; //^代表字符串开头,$代表字符串结尾,\u4e00-\u9fa5是汉字 pattern="^[\u4e00-\u9fa5][0-9]$";//匹配的格式两个字符,以汉字开头,数字结尾 Pattern r1=Pattern.compile(pattern); Matcher m3=r1.matcher(str1); Matcher m4=r1.matcher(str2); System.out.println(m3.matches());//true System.out.println(m4.matches());//false //==================================================== str1="1"; str2="中"; str3="1中"; pattern="^[\u4e00-\u9fa50-9]$";//匹配的格式是一个字符,汉字或者数字 Pattern r2=Pattern.compile(pattern); Matcher m5=r2.matcher(str1); Matcher m6=r2.matcher(str2); Matcher m7=r2.matcher(str3); System.out.println(m5.matches());//true System.out.println(m6.matches());//true System.out.println(m7.matches());//false //====================================== str1="123456中8"; str2="123456789"; //{8}代表匹配8次,长度=8,{8,}代表匹配8次以上,长度>= pattern="^[\u4e00-\u9fa50-9]{8}$";// Pattern r3=Pattern.compile(pattern); Matcher m8=r3.matcher(str1); Matcher m9=r3.matcher(str2); System.out.println(m8.matches());//true System.out.println(m9.matches());//false }