How to find all the occurrences of a word when it is not preceded by another?


How to find all occurrences of a word when not preceded by another? So for example, I want to be able to find all instances of 'sugar' but not 'blood sugar'.

In the following:

Increase in sugar will cause an increase in blood sugar and any more sugar consumed will ...

The above should make 2 matches and not 3

Many thanks in advance

If your regex language supports negative look behinds, you can use (?<!blood )sugar to handle the case without any case sensitive issues. Depending on the language, you can add a flag to the regex to provide case insensitivity. This will allow you to find all cases of your condition using any weird combination of upper and lower case letters. I used your example for testing here.

The regex is simple, a negative look behind (?<!blood ) of the string you are looking for sugar. This will match your string only if it is NOT preceded by blood. The space does not need to be returned with the match, so it is included as part of the look behind, instead of before suguar.