-1

Assuming YES, OR and YES are random words (provided that the 2 YES are the same) and are only here for representation :

I am trying to use regex to match YES, OR and YES in any place, with the condition that the string must only match if it has 2 YES.

So if i try to use the following test strings :

yes or yes
no or yes
yes or no
maybe yes or yes
maybe yes or no
yes maybe or yes
maybe yes maybe yes maybe or

It should only match the following :

yes or yes
maybe yes or yes
yes maybe or yes
maybe yes maybe yes maybe or

Here's my regex query which I am working on :

^(?=.*(?=\w.*yes)(?=\w.*or)(?=\w.*yes)).*

Unfortunately, my query still matches no or yes. Here's my regex link : Click Here

2 Answers2

0

Why not so?

^(?=.*\byes\b.+\byes\b)(?=.*\bor\b).+

The first Positive Lookahead finds two yes, and the second one matches or

demo on regex101

splash58
  • 25,216
  • 3
  • 19
  • 31
0

A non-regex way using substr_count()

<?php
$string = 'yes or yes
no or yes
yes or no
maybe yes or yes
maybe yes or no
yes maybe or yes
maybe yes maybe yes maybe or';
$array =   explode("\n", $string);
$expected = [];
//print_r($array);
foreach($array as $line){
    $words = substr_count($line,'yes');
    if($words==2 && strpos($line, 'or') !== false ){
     $expected[]= $line;   
    }
}

echo implode("\n",$expected);

Output:

yes or yes
maybe yes or yes
yes maybe or yes
maybe yes maybe yes maybe or

DEMO: https://3v4l.org/uL7fJ

Always Sunny
  • 29,081
  • 6
  • 43
  • 74