Home > Software design >  regex negative lookahead of optional word
regex negative lookahead of optional word

Time:09-29

I want to match if the string has APPLE BANANA an optional CARROT as long as CARROT is not followed by VEGETABLE

My test strings, first ones should match, last one should not

APPLE BANANA CARROT FRUIT
APPLE BANANA VEGETABLE FRUIT
APPLE BANANA NOT FRUIT
APPLE BANANA CARROT 
APPLE BANANA CARROT FRUIT VEGETABLE

APPLE BANANA CARROT VEGETABLE FRUIT

I've gotten this which is CARROT required: APPLE BANANA (CARROT\s )(?!VEGETABLE)

https://regex101.com/r/uZQOA7/4

But when I try to make (CARROT\s ) optional like (CARROT\s )? it isn't doing what I thought it should do. I'm missing something here.

CodePudding user response:

You can put the check in the lookahead, checking that after BANANA there is not CARROT VEGETABLE. If that is the case, then match an optional CARROT.

\bAPPLE BANANA(?!\s CARROT\s VEGETABLE\b)(?:\s CARROT\b)?

Regex demo

  • Related