これを解決するために正規表現の助けを借りることができると思います。次のようなコードを検討してください。
String arr[] = {"12341234abc", "1234foo1234", "12121212", "111111111", "1a1212b123123c12341234d1234512345"};
String regex = "(\\d+?)\\1";
Pattern p = Pattern.compile(regex);
for (String elem : arr) {
boolean noMatchFound = true;
Matcher matcher = p.matcher(elem);
while (matcher.find()) {
noMatchFound = false;
System.out.println(elem + " got repeated: " + matcher.group(1));
}
if (noMatchFound) {
System.out.println(elem + " has no repeation");
}
}
出力:
abc12341234abc got repeated: 1234
1234foo1234 has no repeation
12121212 got repeated: 12
12121212 got repeated: 12
111111111 got repeated: 1
111111111 got repeated: 1
111111111 got repeated: 1
111111111 got repeated: 1
1a1212b123123c12341234d1234512345 got repeated: 12
1a1212b123123c12341234d1234512345 got repeated: 123
1a1212b123123c12341234d1234512345 got repeated: 1234
1a1212b123123c12341234d1234512345 got repeated: 12345
説明:
使用されている正規表現は(\\d+?)\\1
どこにありますか
\\d - means a numerical digit
\\d+ - means 1 or more occurrences of a digit
\\d+? - means reluctant (non-greedy) match of 1 OR more digits
( and ) - to group the above regex into group # 1
\\1 - means back reference to group # 1
(\\d+?)\\1 - repeat the group # 1 immediately after group # 1