Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex match if string contain all the words or a condition

Tags:

regex

im making a simple word game with php and regex, how can we search that if a string have to require two or more words?

lets say

"cat"
"dog"
"play" x 2

if

"cat dog play play" pass

"hello a cat dog playing a play" not pass, only 1 "play"

"cat" not pass, no dog and 2x play

"i want a cat and a dog play with me and play with grandfather" pass

how can we match it with regex?

like image 766
Adam Ramadhan Avatar asked Jan 17 '23 12:01

Adam Ramadhan


1 Answers

The regex you're looking for is:

/(?=.*?\bcat\b)(?=.*?\bdog\b)(?=(.*?\bplay\b){2})^.*$/

Explanation: I believe words cat, dog and play (twice) can appear in the text in any order but they must all be present in the sentence to qualify. Above regex is using positive lookahead to make sure the presence of above conditions.

Here is the online working demo of above RegEx

like image 188
anubhava Avatar answered Jan 19 '23 02:01

anubhava