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

后端 未结 5 1131
借酒劲吻你
借酒劲吻你 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:16

    You can use this positive lookahead based regex:

    ((\\w)\\2+)(?=.*\\1)
    

    Code:

    String elem = "aaabbaaacccbb";
    String regex = "((\\w)\\2+)(?=.*\\1)";
    Pattern p = Pattern.compile(regex);
    Matcher matcher = p.matcher(elem);
    for (int i=1; matcher.find(); i++)
    System.out.println("Group # " + i + " got: " + matcher.group(1));
    

    OUTPUT:

    Group # 1 got: aaa
    Group # 2 got: bb
    

提交回复
热议问题