Vladislav Latish
Vladislav Latish

Reputation: 317

Need regexp with condition

It is necessary to check string. It should contain one substring AND dont contain other substring. This should works only with regexp.

Examples. We accept string with 'fruit' substring, but don't accept string contains substring 'love':

We all love green fruit. -> dont match
We all love to walk. -> dont match
We all green fruit. -> match

Write one regex if it possible.

/(?<!love).+fruit/ dont work

Upvotes: 1

Views: 59

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627507

Surely, you can achieve what you want with strpos, but you specified you only need a regex solution. Note that this is not the best approach for this task unless you need to check for the substrings in a specific context (like within word boundaries, or after or before specific symbols, etc.)

The (?<!love).+fruit regex matches any 1+ characters that are not preceded with love substring up to the fruit substring. It will match I love fruit because the lookbehind asserts true at the beginning of the string, then .+ grabs the whole string, then backtracking does its job to get fruit.

In fact, you only need 1 lookahead to check if there is no love anchored at the start of the string:

^(?!.*love).*fruit
 ^^^^^^^^^^

See the regex demo

You only check for the substring love with (?!.*love) at the beginning of the string (due to ^), and then, if it is missing, the regex goes on matching any characters (other than a newline if /s modifier is not use) up to the last fruit.

Here is a PHP demo:

$re = "/^(?!.*love).*fruit/"; 
if (preg_match($re, "We all love green fruit."))
{ 
   echo "Matched!";  // Won't be displayed since there is no match
}

Upvotes: 2

rock321987
rock321987

Reputation: 11042

I think this will work

^(?!.*\blove\b)(?=.*\bfruit\b).*
 <------------><------------->
   Don't match    Match this
    this word        word

Regex Demo

NOTE :- You can remove \b if you assume to match substring..

Upvotes: 3

Related Questions