In this Remove consecutive duplicate words, we would take
"alpha beta beta gamma gamma gamma delta alpha beta beta gamma gamma gamma delta"
as a input string, and output.
"alpha beta gamma delta alpha beta gamma delta"
One of the solution I saw was. very elegant but I still struggle with the regex
public class Kata {
public static String removeConsecutiveDuplicates(String s){
return s.replaceAll("(\b\S+)( \1\b)+", "$1");
}
}
\b
means the word boundary. \s+
means. one or more empty spaces.
( \1)
means the first group ie (\b\S+)
. ( \1\b)+
means matching first group and a duplicate word, correct? I am sure what the empty space in ( \1\b)+
does actually.
I didn’t try anything.
Rob is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.