日期:2014-05-20 浏览次数:20867 次
//汉字范围u4E00-u9FA5
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class sxtRegex01 {
public static void main(String[] args) {
p("检查是否匹配:"+"abc".matches("..."));
p("替换字符串:"+"abc123aa".replaceAll("\\d", "."));
Pattern p = Pattern.compile("[a-z]{3}");
Matcher m = p.matcher("fgha");
p("Pattern+Matcher方法验证匹配:"+m.matches());
p("------------------");
p("a".matches("[abc]"));
p("a".matches("[^abc]"));
p("A".matches("[a-zA-Z]"));
p("A".matches("[a-z]|[A-Z]"));
p("A".matches("[a-z(A-Z)]"));
p("R".matches("[A-Z&&(RFG)]"));
p("------------------");
p("a_8".matches("\\w{3}"));
p("\\".matches("\\\\"));
p("------------------");
p("hello sir".matches("h.*"));
p("hello sir".matches(".*ir$"));
p("hello sir".matches("^h[a-z]{1,3}o\\b.*"));//匹配单词边界,单词边界是空格出现的位置用\\b匹配
p("hellosir".matches("^h[a-z]{1,3}o\\b.*"));
p(" \n".matches("^[\\s&&[^\\n]]*\\n$"));//开头是一个空格,且不能是换行符,最后必须是换行
p("------------------");
Pattern p2 = Pattern.compile("\\d{3,5}");
String s = "123-4536-89789-000";
Matcher m2 = p2.matcher(s);
p(m2.matches());
m2.reset();//把吃进去的字符吐出来重新匹配,否经过m2.matches会吃进去字符 下面的匹配就不成功
p(m2.find());
p(m2.start()+"-"+m2.end());//找到了 就把首位位置打印下(必须找到才能打印)
p(m2.find());
p(m2.start()+"-"+m2.end());
p(m2.find());
p(m2.start()+"-"+m2.end());
p(m2.find());
p(m2.lookingAt());//每次都是才头上开始找
p("------------------");
Pattern p3 = Pattern.compile("java",Pattern.CASE_INSENSITIVE);//加属性后,Patter.CASE_INSENSITIVE表示大小写不管
Matcher m3 = p3.matcher("java_Java_jAva_jAVa_IloveJava");
p(m3.replaceAll("JAVA"));//把所有的都替换为大写的
p("------------------按照单双数替换");
Pattern p4 = Pattern.compile("java",Pattern.CASE_INSENSITIVE);//加属性后,Patter.CASE_INSENSITIVE表示大小写不管
Matcher m4 = p4.matcher("java_Java_jAva_jAVa_IloveJava fdasfas");
StringBuffer sb = new StringBuffer();
int i = 0;
while(m4.find()){
i ++;
if(i%2 == 0){
m4.appendReplacement(sb, "java");
}else{
m4.appendReplacement(sb, "JAVA");
}
}
m4.appendTail(sb);//把尾巴在再添加到buf上既是sb
p(sb);
p("------------------分组加括号只取数字一组");