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

后端 未结 5 1141
借酒劲吻你
借酒劲吻你 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 20:57

    This seems to work, though it gives subsequences as well:

    (To be fair, this was built off of Guillame's code)

    public static void main(final String[] args) {
        // final String s = "RonRonJoeJoe";
        // final String s = "RonBobRonJoe";
        final String s = "aaabbaaacccbb";
    
        final Pattern p = Pattern.compile("(.+).*\\1");
    
        final Matcher m = p.matcher(s);
        int start = 0;
        while (m.find(start)) {
            System.out.println(m.group(1));
            start = m.toMatchResult().end(1);
        }
    }
    

提交回复
热议问题