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:
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>' });
If you want to find multiple words right after each other, for example,
Sam
went went
to to to
his business
you can use this regex:
s = "Sam went went to to to his business";
a = s.match(/\b(\w+)(\s\1)+\b/g);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With