Home > Software engineering >  Regex matching all the giving letter at any position one or multiple times
Regex matching all the giving letter at any position one or multiple times

Time:02-22

I'm trying to use a regex that matches all giving letter at any position one or multiple times, for example:

if user the input elol the result should be:

ollie Leola  cello  gello
hello   jello
lobel
lorel   losel
molle   oller

right now I have this:

.*elol

but it's not working because it doesn't match the letters in different positions in the words

the idea came from this site: https://www.wordhippo.com/what-is/word-finder-unscrambler.html (just search for words in the Containing the letters (in any position) input)

CodePudding user response:

Use look aheads for each letter:

(?=\w*e)(?=\w*o)(?=(?:\w*l){2})\w 

See live demo.

Note that when a letter must appears multiple times, you must add an appropriate quantifier.

CodePudding user response:

You can start the pattern with a word boundary \b to prevent the lookahead firing on every position when trying to find a match.

Then you can use a negated character class matching optional word chars excluding the one that should match like [^\We] and then match the wanted char to prevent some unnecessary backtracking.

\b(?=[^\We]*e)(?=[^\Wo]*o)(?:[^\Wl]*l){2}\w*
  • \b A word boundary
  • (?=[^\We]*e) Assert an e char
  • (?=[^\Wo]*o) Assert an o char
  • (?:[^\Wl]*l){2} Match 2 times an l char
  • \w* Match optional word chars

Regex demo

  • Related