Uday Kumar
Uday Kumar

Reputation: 1

How to Remove Case-Insensitive Repeated Words in a Sentence Using Regular Expressions?

Question details:

I'm solving the HackerRank Regex - Duplicate Words problem in Java where the goal is to use regular expressions to remove repeated words while retaining the first occurrence, regardless of case. For example, the input "I love Love to To tO code" should output as "I love to code."

For solving the problem we have to complete the below three lines:

  1. Write a RegEx to match repeated words.

  2. Add a compile argument to make the RegEx case-insensitive.

  3. Use replaceAll to replace duplicates with the first occurrence, keeping the original case of the first word.

Problems Code [which I've solved]:

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DuplicateWords {

    public static void main(String[] args) {

        // RegEx to match repeated words
        String regex = "\\b(\\w+)\\b(?:\\s+\\b\\1\\b)+";
        Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);

        Scanner in = new Scanner(System.in);
        int numSentences = Integer.parseInt(in.nextLine());
        
        while (numSentences-- > 0) {
            String input = in.nextLine();
            
            Matcher m = p.matcher(input);
            
            // Check for subsequences of input that match the compiled pattern
            while (m.find()) {
                // Replace the repeated words with a single occurrence of the word
                input = input.replaceAll(m.group(), m.group(1));
            }
            
            // Prints the modified sentence.
            System.out.println(input);
        }
        
        in.close();
    }
}

Input [stdin]:

  1. 5
    
  2. Goodbye bye bye world world world
    
  3. Sam went went to to to his business
    
  4. Reya is is the the best player in eye eye game
    
  5. in inthe
    
  6. Hello hello Ab aB
    

Output [I'm getting]:

  1. Goodbye bye world
    
  2. Sam went to his business
    
  3. Reya is the best player in eye game
    
  4. in inthe
    
  5. Hello Ab
    

Expected Output [The output that needs to be shown on the output screen]:

  1. Goodbye bye world
    
  2. Sam went to his business
    
  3. Reya is the best player in eye game
    
  4. in inthe
    
  5. Hello Ab
    

Problem that I'm facing:
In the above code I've satisfied all the rules and my code has matched the expected output. Even though it is showing error in the output screen.

Upvotes: 0

Views: 46

Answers (0)

Related Questions