java 正则表达式测试

来源:互联网 发布:无需网络的手机电视 编辑:程序博客网 时间:2024/05/22 01:36
package net.heartsome.token;


import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class RegexTest {


/**
* @param args
*            ;
*/
public static void main(String[] args) {
test1();
test2();
test3();
test4();
test5();
test6();
test7();
}


// 匹配单位测试 :一个表达式表示一次匹配的单元(默认使用贪婪匹配,他们会尽可能多的匹配)


public static void test1() {
String src = "<a> </b> </a> <b> 2s d f d </b> f a b<b>sdf</b>";
// 1、所有的字符都是 "普通字符",那么这个表达式的匹配操作,实际上就是一个普通的 "字符串查找" 操作
// 以a 为匹配单位
showResult(src, "a");
// 以<a> 为单位
showResult(src, "<a>");
// 2 、转义字符,匹配特殊字符 ,比如 : . * [ ] { }
String src1 = ": . * [ * ] { } [ ] (a+b)*3 (A+b)*3 (a+B)*3 (A+B)*3";
showResult(src1, "\\[");
// 2.1 \Q \E java 只支持这一个
showResult(src1, "\\Q(a+b)*3\\E");
// \p{javaLowerCase} :匹配所有小写字母
showResult(src1, "\\p{javaLowerCase}");
// \p{javaLowerCase} :匹配所有大写字母
showResult(src1, "\\p{javaUpperCase}");


// 字符集合[a-z] :默认是或者的关系


}


// 匹配次数的限定


public static void test2() {
String src = "aa bb aaa bba sf";
// 表示重复两次
showResult(src, "a{2}");
String src1 = "aa bbasff aaa bba sf";
showResult(src1, "b{2}a");


String src2 = "aa bbasff aaa bba sf ba abb ab";


showResult(src2, "b{1,2}a");
showResult(src2, "ab{1,}");


}


// “勉强模式”限定符?:总是尽可能少的匹配
public static void test3() {
String src = "sssss badfgd";
showResult(src, "s{1,3}?");
}


// “勉强模式”限定符+:总是可能多的匹配和默认的匹配一样
// 区别:当匹配失败的时候不会回退字符
public static void test4() {
String src0 = "xfooxxxxxxfoo";
// no results is here
showResult(src0, ".*+f");
// the result is : xfooxxxxxxf
showResult(src0, ".*f");
}


// 分组
public static void test5() {
String src = "sssssbsbsbsadfgd";
showResult(src, "(sb){1,3}s");
}


// 非捕获分组,不保留结果,要节约资源一点
public static void test6() {
String src = "sssssbsbsbsadfgd";
showResult(src, "(?:sb){1,3}s");


}
    // 非贪婪使用,匹配*foo的个数
// 就是满足foo前面的字符最少的情况
public static void test7() {
String src = "xfooxxxxxxfoo";
showResult(src, ".*?foo");


}
public static void showResult(String src, String regex) {
Pattern p = Pattern.compile(regex);
Matcher matcher = p.matcher(src);
while (matcher.find()) {
System.out.println(matcher.group());
}
System.out.println("group count:"+matcher.groupCount());
}
}