Regex repeated words on the same line

regex

Solution

This regex will do to find which words you want to highlight. (The example is in JavaScript, and it is easy to test in the browser's JavaScript console.)

s = "It's a foo and a bar and a bar and a foo too.";
a = s.match(/\b(\w+)\b(?=.*\b\1\b)/g);

This returns an array of words, possibly multiple times for the same word.

Next you can do this:

re = new RegExp('\\b(' + a.join('|') + ')\\b', 'g');

And that should suffice to highlight all occurrences:

out = s.replace(re, function(m) { return '<b>' + m + '</b>' });

Problem

What is the regular expression to find words that are repeated on the same line? I've tried some expressions that I found on Stack Overflow, such as this, but none is working correctly. The result I want to achieve:

Original source

Related problems