Home > Software engineering >  Regex capture required and optional characters in any position only
Regex capture required and optional characters in any position only

Time:11-29

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

Example:

  • Optional letters: yujkfec
  • Required letter: d

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.

CodePudding user response:

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.
  • Related