正则表达式中的分组
正则表达式可以通过" () “来进行分组,更专业的表达就是捕获组,每个完整的” () “可以分为一组,同时,” () “中还可以嵌套” () ",即组之间还可以存在更小的组,以此类推。而编号为0的组,则是正则表达式匹配到的整体,这个规则只要支持正则表达式中捕获组的语言基本上都适用,下面举几个简单实用的小例子
public class Demo7_Regex {
public static void main(String[] args) {
String regex1 = "(.)\\1(.)\\2";
System.out.println("高高兴兴".matches(regex1));
System.out.println("快快乐乐".matches(regex1));
System.out.println("高兴高兴".matches(regex1));
String regex2 = "(..)\\1";
System.out.println("高兴高兴".matches(regex2));
System.out.println("快乐快乐".matches(regex2));
System.out.println("高高兴兴".matches(regex2));
String regex3 = "(.)\\1+";
String s1 = "sdqqfqkkkmhppppas";
String[] arr = s1.split(regex3);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]+" ");
}
System.out.println("===============================");
String regex4 = "\\.";
String s2 = "我我..要要要....学..学......学编...编编..程程..";
String s3 = s2.replaceAll(regex4, "");
System.out.println(s3);
String s4 = s3.replaceAll("(.)\\1+", "$1");
System.out.println(s4);
}
}