Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex repeated words on the same line

Tags:

regex

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:

Enter image description here

like image 499
PoseLab Avatar asked Nov 30 '22 21:11

PoseLab


2 Answers

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>' });
like image 63
bart Avatar answered Dec 16 '22 09:12

bart


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);
like image 35
Aryeetey Solomon Aryeetey Avatar answered Dec 16 '22 07:12

Aryeetey Solomon Aryeetey