Regex to exclude [ unless preceded by \

java, regex

Solution

This will match all characters that are either not equal to `[` or equal to a `[` preceded by `\`:

([^\[]|(?<=\\)\[)+

If you want a simple pass/fail for an entire string, just add the start/end-line characters to the regex:

^([^\[]|(?<=\\)\[)+$

Problem

How do I write a regex that accepts an expression that contains any number of any characters except for '`[`', unless '`[`' is preceded by '`\`' ? Example: ``` this is text \\[ this also [$ this isn't any more ``` From the above text, "`this is text \\[ this also`" should be accepted, and the rest shouldn't. I wrote something like: ``` [.[^\\\\[]]* ``` to exclude the '`[`' but have no idea how to allow it to contain '`\\[`' and the rest of the text also.

Original source