方法解析 matches():匹配整个字符串 find():匹配子字符串 lookingAt():永远从整个字符串的开头开始匹配 //email p("asdsfdfagf@adsdsfd.com".matches("[\\w[.-]]+@[\\w[.-]]+\\.[\\w]+"));//true //matches() find() lookingAt() Pattern p = Pattern.compile("\\d{3,5}"); Matcher m = p.matcher("123-34345-234-00"); //将整个"123-34345-234-00"用正则表达式引擎查找匹配,当到第一个"-"不匹配了,就停止, //但不会将不匹配的"-"吐出来 p(m.matches()); //将不匹配的"-"吐出来 m.reset(); //1:当前面有p(m.matches());查找子字符串从"...34345-234-00"开始 //将会是第1,2两个查到"34345"和"234" 后面2个查不到为false //2:当前面有p(m.matches());和m.reset();查找子字符串从"123-34345-234-00"开始 //将为true,true,true,false p(m.find()); p(m.start()+"---"+m.end()); p(m.find()); p(m.start()+"---"+m.end()); p(m.find()); p(m.start()+"---"+m.end()); p(m.find()); //要是没找到就会报异常java.lang.IllegalStateException //p(m.start()+"---"+m.end()); p(m.lookingAt()); p(m.lookingAt()); p(m.lookingAt()); p(m.lookingAt()); 字符串替换:下面这种方法对于字符串替换非常灵活 //字符串替换 //Pattern.CASE_INSENSITIVE大小写不敏感 Pattern p = Pattern.compile("java",Pattern.CASE_INSENSITIVE); Matcher m = p.matcher("java Java jAva ILoveJavA youHateJAVA adsdsfd"); //存放字符串 StringBuffer buf = new StringBuffer(); //计数奇偶数 int i = 0; while(m.find()){ i++; if(i%2 == 0){ m.appendReplacement(buf, "java"); }else{ m.appendReplacement(buf, "JAVA"); } } //不加这句话,字符串adsdsfd将会被遗弃 m.appendTail(buf); p(buf); 运行结果: JAVA java JAVA ILovejava youHateJAVA adsdsfd //group分组,用()分组 Pattern p = Pattern.compile("(\\d{3,5})([a-z]{2})"); String s = "123aa-34345bb-234cc-00"; Matcher m = p.matcher(s); p(m.groupCount());//2组 while(m.find()){ p(m.group());//数字字母都有 //p(m.group(1));//只有数字 //p(m.group(2));//只有字母 } 基础持续更新-------正则表达式
|