1
votes

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).

1

1 Answers

3
votes

There is no single plain regex solution to this problem because you need a lookbehind with a backreference inside, which is not supported by Java regex engine.

What you can do is either get all (\w)\1+ matches and then check their length using common string methods:

String s = "aaabbaa";
Pattern pattern = Pattern.compile("(\\w)\\1+");
Matcher matcher = pattern.matcher(s);
while (matcher.find()){
    if (matcher.group().length() == 2) System.out.println(matcher.group(1)); 
} 

(see the Java demo) or you can match 3 or more repetitions or just 2 repetitions and only grab the match if the Group 2 matched:

String s = "aaabbaa";
Pattern pattern = Pattern.compile("(\\w)\\1{2,}|(\\w)\\2");
Matcher matcher = pattern.matcher(s);
while (matcher.find()){
    if (matcher.group(2) != null)
        System.out.println(matcher.group(2)); 
} 

See this Java demo. Regex details:

  • (\w)\1{2,} - a word char and two or more occurrences of the same char right after
  • | - or
  • (\w)\2 - a word char and the same char right after.