Chad Miles
Chad Miles

Reputation: 83

Regex capture required and optional characters in any position only

I would like to match against a word only a set of characters in any order but one of those letters is required.

Example:

Matches: duck dey feed yudekk dude jude dedededy jejeyyyjd
No matches (do not contain required): yuck feck
No matches (contain letters outside of set): sucked shock blah food bard

I've tried ^[d]+[yujkfec]*$ but this only matches when the required letter is in the front. I've tried positive lookaheads but this didn't do much.

Upvotes: 1

Views: 23

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626952

You can use

\b[yujkfec]*d[dyujkfec]*\b

See the regex demo. Note that the d is included into the second character class.

Details:

  • \b - word boundary
  • [yujkfec]* - zero or more occurrences of y, u, j, k, f, e or c
  • d - a d char
  • [dyujkfec]* - zero or more occurrences of y, u, j, k, f, e, c or d.
  • \b - a word boundary.

Upvotes: 1

Related Questions