简体   繁体   中英

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:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM