Aaron Magpantay
Aaron Magpantay

Reputation: 405

Match words using set of letters with one instance

Had this problem thinking on how I should do this, I am playing some word games and I want to match words in a set of dictionary words with 5 letters I tried something like this

\b[clagey]{5}\b

it is good, but it is matching word like "eagle". The Problem is I want a single instance on each letters c,l,a,g,e,y not "eagle" with double e's.

Upvotes: 4

Views: 148

Answers (1)

Gurmanjot Singh
Gurmanjot Singh

Reputation: 10360

Try this Regex:

\b(?:([clagey])(?!\S*\1)){5}\b

Click for Demo

Explanation:

  • \b - a word-boundary
  • ([clagey]) - matches one of these characters - c, l, a, g, e, y and captures it in group 1
  • (?!\S*\1) - negative lookahead too make sure that whatever is captured in group 1 is not repeated before the occurrence of next white-space
  • {5} - to match 5 occurrences
  • \b - a word boundary

Upvotes: 4

Related Questions