Question: Print character(s) in a string that are repeated consecutively only twice (not more).
Examples:
1)"aaabbaa" : b and a
2)"aabbaa" : a and b and a
3)"abba" : b
Code I tried:
String str = "aabbbbcccd";
Pattern p = Pattern.compile("(\w){2}");
Matcher m = p.matcher(str);
while(m.find())
{
System.out.println(m.group(1));
}
Output:
a
b
b
c
d
Although, the desired output is
a
d
Postscript
As I have recently started with regex, it would highly appreciated if the answerer can explain
the regex used briefly (especially quantifiers and groups).