I'm trying to find all the duplicate elements in a sentence.
To do this, I am testing with the following code, but I only detect the first duplicate word and I would like to replace all of them, regardless of whether they are uppercase or lowercase.
This is my code:
public static void main(String[] args) {
String regex = "\b(\w+)\s+\1\b+";
Pattern p = Pattern.compile(regex,Pattern.CASE_INSENSITIVE /* Insert the correct Pattern flag here.*/);
Scanner in = new Scanner(System.in);
String input = in.nextLine();
Matcher m = p.matcher(input);
while (m.find()) {
input = input.replaceAll(m.group(), m.group(1));
}
// Prints the modified sentence.
System.out.println(input);
}
For example, in the sentence:
Hola hola hOla
You should print only:
Hola
Currently I print:
Hola hOla