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
Algorithm. Construct a string pattern adding the input string str twice. Remove the first and last characters in the pattern. Find for str in the pattern, if the match is found return True else return False.
The most important term is congruent which is equivalent to saying that a repeating pattern has identical units of repeat. Other useful terms are rectangle and parallel. Most repeating patterns in the environment occur in manufactured objects. Some examples are tiles, pavers, windows, zebra crossings and railway lines.
This problem can also be solved using the fact that we can search for root string after adding a string and checking the root string in this string except last and first character, represents the string is repeating itself.
If you use regex, you only need one line:
String repeated = str.replaceAll("(.+?)\\1+", "$1");
Breaking down the regex (.+?)\1
:
(.+?)
means "at least one character, but as few as possible, captured as group 1"\1
means "the same character(s) as group 1Here's some test code:
String[] strs = {"AAAAAAAAA", "ABABAB", "ABCAB", "ABAb"};
for (String str : strs) {
String repeated = str.replaceAll("(.+?)\\1+", "$1");
System.out.println(repeated);
}
Output:
A
AB
ABCAB
ABAb
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With