HackerRank Java- Regex 2 - Duplicate Words



In this challenge, we use regular expressions (RegEx) to remove instances of words that are repeated more than once, but retain the first occurrence of any case-insensitive repeated word. For example, the words love and to are repeated in the sentence I love Love to To tO code. Can you complete the code in the editor so it will turn I love Love to To tO code into I love to code?

To solve this challenge, complete the following three lines:

Write a RegEx that will match any repeated word.
Complete the second compile argument so that the compiled RegEx is case-insensitive.
Write the two necessary arguments for replaceAll such that each repeated word is replaced with the very first instance the word found in the sentence. It must be the exact first occurrence of the word, as the expected output is case-sensitive.



  1. import java.util.Scanner;
  2. import java.util.regex.Matcher;
  3. import java.util.regex.Pattern;
  4. public class DuplicateWords {
  5. public static void main(String[] args) {
  6. String regex = "\\b(\\w+)(?:\\W+\\1\\b)+";
  7. Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
  8. Scanner in = new Scanner(System.in);
  9. int numSentences = Integer.parseInt(in.nextLine());
  10. while (numSentences-- > 0) {
  11. String input = in.nextLine();
  12. Matcher m = p.matcher(input);
  13. // Check for subsequences of input that match the compiled pattern
  14. while (m.find()) {
  15. input = input.replaceAll(m.group(), m.group(1));
  16. }
  17. // Prints the modified sentence.
  18. System.out.println(input);
  19. }
  20. in.close();
  21. }
  22. }

download android app