Although it's unlikely you could do this with a MySQL regular expression, and I think it would be better approached using another language, you could write a MySQL function to do this.
There's probably any number of approaches. This one loops over all the occurrences of needle
in haystack
, checking whether the number of {
characters preceding the occurrence is less than or the same as the number of }
characters preceding it. Which means it's not particularly robust (}}}{JELLY2}
would confuse it) but you could develop the idea further if this was an issue.
DELIMITER //
CREATE FUNCTION contains_text_outside_braces(needle VARCHAR(255), haystack VARCHAR(255))
RETURNS INT DETERMINISTIC
BEGIN
DECLARE pos INT;
DECLARE previous INT DEFAULT 1;
DECLARE length INT DEFAULT LENGTH(needle);
DECLARE prefix VARCHAR(255);
LOOP
SET pos = LOCATE(needle, haystack, previous);
IF pos = 0 THEN
RETURN 0;
END IF;
SET prefix = LEFT(haystack, pos - 1);
IF LENGTH(REPLACE(prefix, '{', '')) >= LENGTH(REPLACE(prefix, '}', '')) THEN
RETURN 1;
END IF;
SET previous = pos + length;
END LOOP;
END//
DELIMITER ;
SELECT * FROM example_table WHERE contains_text_outside_braces('JELLY2', content);