JAVA foundation (Regular Expressions - grouping function)

1, the regular expression grouping function

  • Capture group which may be opened by the bracket numbered left to right. For example, in the expression ((A) (B (C))), there are four such groups:

        1    ((A)(B(C)))

        2     (A

        3     (B(C))

        4     (C)

        Group zero always represents the entire expression.

public static void demo1() {

        //叠词 快快乐乐,高高兴兴

        /*String regex = "(.)\\1(.)\\2";                    //\\1代表第一组又出现一次    \\2代表第二组又出现一次

        System.out.println("快快乐乐".matches(regex));

        System.out.println("快乐乐乐".matches(regex));

        System.out.println("高高兴兴".matches(regex));

        System.out.println("死啦死啦".matches(regex));*/

        

        //叠词 死啦死啦,高兴高兴

        String regex2 = "(..)\\1";

        System.out.println("死啦死啦".matches(regex2));

        System.out.println("高兴高兴".matches(regex2));

        System.out.println("快快乐乐".matches(regex2));

    }

2, cutting

[1] Required: Please cut to fold word: "sdqqfgkkkhjppppkl";

[2] replace

  • Requirements: I ... I .... I want to ... I want to ... learn to learn .... .. .. compiled code compiled learn programming Cheng Cheng ........ journey

  •  Restore string into: "I want to learn programming."

public static void main(String[] args) {

        /*

         * 需求:我我....我...我.要...要要...要学....学学..学.编..编编.编.程.程.程..程

                将字符串还原成:“我要学编程”。

         */

        String s = "我我....我...我.要...要要...要学....学学..学.编..编编.编.程.程.程..程";

        String s2 = s.replaceAll("\\.+", "");

        String s3 = s2.replaceAll("(.)\\1+", "$1");    //$1代表第一组中的内容

        System.out.println(s3);

    }





    public static void demo2() {

        //需求:请按照叠词切割: "sdqqfgkkkhjppppkl";

        String s = "sdqqfgkkkhjppppkl";

        String regex = "(.)\\1+";                    //+代表第一组出现一次到多次

        String[] arr = s.split(regex);

        

        for (int i = 0; i < arr.length; i++) {

            System.out.println(arr[i]);

        }

    }

 

Guess you like

Origin blog.csdn.net/Cricket_7/article/details/92803068