I was working on a problem recently to remove repeating words in a String, i.e "i am am good" becomes "i am good". But I noticed something strange, the Regex works for all different cases except one and I don't understand why.

Here is my code:

```
        String regex = "\\b(\\w+)(\\s+\\1\\b)+";
        Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);

        String input = "INPUT";

        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);

```

Now once given the INPUT: 

> 
> i am am 2 am am am 1 am a good man
> 
> 
> 

OUTPUT:

> 
> i am 2 am am 1 am a good man
> 
> 
> 

still has two repeating "am".
Now if INPUT is:

> 
> i am am 2 am am am 1 am am a good man
> 
> 
> 

OUTPUT:

> 
> i am 2 am 1 am a good man
> 
> 
> 

No repeating "am"

I can't figure out why is that, can anyone help?