Find duplicate pattern in string

How to find a repeating pattern in a string? For example, if the input file was

AAAAAAAAA
ABABAB
ABCAB
ABAb

he outputs:

A
AB
ABCAB
ABAb
+3
source share
4 answers

This prints out what you ask for - the regex could probably be improved to avoid a loop, but I can't 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;
}
+1
source

If you use regex, you only need one line:

String repeated = str.replaceAll("(.+?)\\1+", "$1");

Regular expression violation (.+?)\1:

  • (.+?) means "at least one character, but as little as possible, captured as group 1"
  • \1 means "same character (s) as group 1

Here are some test codes:

String[] strs = {"AAAAAAAAA", "ABABAB", "ABCAB", "ABAb"};
for (String str : strs) {
    String repeated = str.replaceAll("(.+?)\\1+", "$1");
    System.out.println(repeated);
}

Conclusion:

A
AB
ABCAB
ABAb
+4
source

#, .

public static string FindPattern(string s)
{
    for (int length = 1; length <= s.Length / 2; length++)
    {
        string pattern = s.Substring(0, length);
        if(MatchesPattern(s, pattern))
        {
            return pattern;
        }
    }
    return s;
}

public static bool MatchesPattern(string s, string pattern)
{
    for (int i = 0; i < s.Length; i++)
    {
        if(!s[i].Equals(pattern[i%pattern.Length]))
        {
            return false;
        }
    }
    return true;
}
0

:

(.+?)(\\ ?\\1)+
0

All Articles