Search code examples
javastringcharacter

Finding a repeated pattern in a string


How can I find a repeated pattern in a string? For example, if the input file were

AAAAAAAAA
ABABAB
ABCAB
ABAb

it would output:

A
AB
ABCAB
ABAb

Solution

  • This outputs what you ask for - the regex can probably be improved to avoid the loop but I can't manage to fix it...

    public static void main(String[] args) {
        List<String> inputs = Arrays.asList("AAAAAAAAA", "ABABAB", "ABCAB", "ABAb");
        for (String s : inputs) System.out.println(findPattern(s));
    }
    
    private static String findPattern(String s) {
        String output = s;
        String temp;
        while (true) {
            temp = output.replaceAll("(.+)\\1", "$1");
            if (temp.equals(output)) break;
            output = temp;
        }
        return output;
    }