Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to find words that contains these letters

I am looking for a regex to find some words that contains some letters. I have the word start, and by regex it should find words that contains (s, two t's, a, r), that has at least 3 letters. So it should return all these words: start, tarts, arts, art. So it should be at least three letters and contains only those characters (s, two t's, a, r).

I tried something like this:

/(([^s]*s){1})(([^t]*t){2})(([^a]*a){1})([^r]*r){1}/g

But this regex does not work, since it requires to be all in this order.

I also tried this one:

[star]{3,}

But it matches any number of characters inside [], ex it matches sss

like image 227
Ertan Hasani Avatar asked Feb 19 '19 17:02

Ertan Hasani


1 Answers

You may use this regex with 2 negative lookahead assertions:

/\b(?!\w*([sar])\w*\1)(?!(?:\w*t){3})[sart]{3,}\b/

RegEx Demo

RegEx Details:

  • \b: Word boundary assertion
  • (?!\w*([sar])\w*\1): Negative lookahead to assert we don't have more than one instance of [sar] letters
  • (?!(?:\w*t){3}): Negative lookahead to assert we don't have more than 2 t letter
  • [sart]{3,}: Match 3+ characters containing [sart] characters
like image 111
anubhava Avatar answered Nov 14 '22 20:11

anubhava