Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

regex negative lookahead of optional word

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading