'how to find any words between 3 to 6 letters long containing either yes or no using regular expression?

I tried:

(no|yes)\w{3,6}

but this basically works, but there is some catch in it. when I say between 3 to 6 characters long, it doesn't count yes or no.

for example: if I have a word yesss, it wont match with it, even though it has only 5 characters. because it starts counting after 'yes'. but it'll match if i have 'yessssss'.

what is the correct regular expression for it?



Solution 1:[1]

You can use

const matches = text.match(/\b(?=\w*(?:yes|no))\w{3,6}\b/ig);

Details:

  • \b - word boundary
  • (?=\w*(?:yes|no)) - after any zero or more word chars, there must be yes or no
  • \w{3,6} - three to six word chars
  • \b - word boundary.

See a JavaScript demo:

const text = "abcno and abcyes and abyesno";
const matches = text.match(/\b(?=\w*(?:yes|no))\w{3,6}\b/ig);
console.log(matches);

If you only want to match words consisting of letters:

const text = "abcno and abcyes and abyesno";
const matches = text.match(/\b(?=\p{L}*(?:yes|no))\p{L}{3,6}\b/igu);
console.log(matches);

The \p{L} matches any Unicode letter and u enables this pattern support in an ECMAScript 2018+ compliant regex engine. If you only work with ASCII letters, replace \p{L} with [a-zA-Z] and remove u flag.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Wiktor Stribiżew