Regular expression - matches all words, but matches unique words only once.

Is it possible to use a regular expression to match all words, but only for unique words? I know that there are other ways to do this, however I am interested in knowing if this is possible using regular expression.

For example, I currently have the following expression:

(\w+\b)(?!.*\1) 

and the following line:

 glass shoes door window door glasses. window glasses 

For the most part, the expression works and matches the following words:

 shoes door window glasses 

There are two problems with this:

  • Matching a substring is done on โ€œglassesโ€ with โ€œglassโ€, this is not true.

  • "glasses" and "glasses". should match, but not at present.

The final match should be:

 shoes door window glasses glass 
+7
source share
2 answers

Pretty close, just read \b in a negative way

 /(\w+\b)(?!.*\1\b)/ 

Look at Rubular

+8
source

Just like maฤek answer , but with an extra \ b before the backlink , otherwise if you have

glass shoes door window door glasses. window glasses sunglasses

You missed the match for points, because he will find it in the word sunglasses.

/(\w+\b)(?!.*\b\1\b)/

+2
source

All Articles