Input: str = “Good bye bye world world”
Output: Good bye world
We remove the second occurrence of bye and world from Good bye bye world world
Input: str = “Ram went went to to to his home”
Output: Ram went to his home
We remove the second occurrence of went and the second and third occurrences of to from Ram went went to to to his home.
Input: str = “Hello hello world world”
Output: Hello world
We remove the second occurrence of hello and world from Hello hello world world.
- Get the sentence.
- Form a regular expression to remove duplicate words from sentences.
regex = "\\b(\\w+)(?:\\W+\\1\\b)+";
The details of the above regular expression can be understood as:
- “\\b”: A word boundary. Boundaries are needed for special cases. For example, in “My thesis is great”, “is” wont be matched twice.
- “\\w+” A word character: [a-zA-Z_0-9]
- “\\W+”: A non-word character: [^\w]
- “\\1”: Matches whatever was matched in the 1st group of parentheses, which in this case is the (\w+)
- “+”: Match whatever it’s placed after 1 or more times
- Match the sentence with the Regex. In Java, this can be done using Pattern.matcher().
- return the modified sentence.
Below is the implementation of the above approach:
Good bye world Ram went to his home Hello world
- std::regex_match, std::regex_replace() | Regex (Regular Expression) In C++
- Check if a binary string has a 0 between 1s or not | Set 2 (Regular Expression Approach)
- Find all the patterns of "1(0+)1" in a given string | SET 2(Regular Expression Approach)
- Find all the numbers in a string using regular expression in Python
- CharBuffer duplicate() method in Java
- LongBuffer duplicate() method in Java
- Regular Expressions in Java
- Buffer duplicate() method in Java with Examples
- ShortBuffer duplicate() method in Java With Examples
- How to find duplicate elements in a Stream in Java
- ByteBuffer duplicate() method in Java with Examples
- DoubleBuffer duplicate() method in Java with Examples
- IntBuffer duplicate() method in Java with Examples
- FloatBuffer duplicate() method in Java with Examples
- smatch | Regex (Regular Expressions) in C++
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.