So I have this string:
My cow always gives milk
My goat sometimes gives milk
My giraffe always gives milk
My goat always buys milk
And this regex:
(?<=cow ).*(?= milk)|(?<=goat ).*(?= milk)
I am matching:
always gives
sometimes gives
always buys
I need to match:
always gives
sometimes gives
How can I add an exception to my regex to prevent matching anything containing the word "buys"? So I only get matches on the first and second line.
>Solution :
One approach would be to use a tempered dot instead of plain .* to match only words which are not buys:
(?<=\bcow )(?:(?!\bbuys\b).)*(?= milk\b)|(?<=\bgoat )(?:(?!\bbuys\b).)*(?= milk\b)
Here is a working demo.
The "new" part of my answer is the following:
(?:(?!\bbuys\b).)*
This says to match, one character at a time, anything, provided that we do not cross the word buys. So, any word will match the above pattern so long as that word is not buys. This is called a "tempered" dot, because, unlike .*, which blindly matches everything, this tempered dot excludes the word buys.