How do I use Java Regex to find all repeating character sequences in a string?

后端 未结 5 1098
借酒劲吻你
借酒劲吻你 2021-01-11 20:38

Parsing a random string looking for repeating sequences using Java and Regex.

Consider strings:

aaabbaaacccbb

I\'d like to find a regular expression

5条回答
  •  暖寄归人
    2021-01-11 21:07

    This does it:

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class Test {
        public static void main(String[] args) {
            String s = "aaabbaaacccbb";
            find(s);
            String s1 = "RonRonRonJoeJoe .... ,,,,";
            find(s1);
            System.err.println("---");
            String s2 = "RonBobRonJoe";
            find(s2);
        }
    
        private static void find(String s) {
            Matcher m = Pattern.compile("(.+)\\1+").matcher(s);
            while (m.find()) {
                System.err.println(m.group());
            }
        }
    }
    

    OUTPUT:

    aaa
    bb
    aaa
    ccc
    bb
    RonRonRon
    JoeJoe
    ....
    ,,,,
    ---
    

提交回复
热议问题