Java Regex 2 - Duplicate Words

Sort by

recency

|

362 Discussions

|

  • + 0 comments

    Java Regex 2 - Duplicate Words challenges users to identify and remove repeated words in a string using regular expressions. It tests proficiency in pattern matching and efficient text processing. Betbhai9 Register

  • + 0 comments

    Please advise on why test case fails even though output matches. I believe its an minor mistake.

    public class DuplicateWords {

    public static void main(String[] args) {
    
        Scanner in = new Scanner(System.in);
        int numSentences = Integer.parseInt(in.nextLine());
    
        while(numSentences > 0)
        {
            String input = in.nextLine();
            List<String> list = Arrays.asList(input.split(" "));
            Set<String> ans = new HashSet<>();  
            String answer = list.stream()
            .filter(str -> ans.add(str.toLowerCase()))
            .collect(Collectors.joining(" ")).trim();        
            System.out.println(answer);
            numSentences--;
        }
    
        in.close();
    }
    

    }

  • + 1 comment

    public class DuplicateWords {

    public static void main(String[] args) {
    
        String regex = "(?i)\\b(\\w+)\\b(?:\\s+\\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()) {
                input = input.replaceAll(regex,"$1");
    
            }
            // Prints the modified sentence.
            System.out.println(input);
        }
    
        in.close();
    }
    

    }

  • + 0 comments

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

    public class DuplicateWords {

    public static void main(String[] args) {
    
        String regex = "\\b(\\w+)(?:\\W+\\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()) {
                input = input.replaceAll(m.group(), m.group(1));
            }
    
            // Prints the modified sentence.
            System.out.println(input);
        }
        in.close();
    }
    

    }

  • + 1 comment

    none of my submitted codes worked, even though the result was the same as expected, and even this code didn't work, unless it was exactly the same as many user submit here. wtf?!