Regex for matching a character, but not when it’s enclosed in square bracket

Assuming there are no nested square brackets, you can use the following to only match - characters that are outside of square brackets:

-(?![^\[]*\])

Example: http://regex101.com/r/sX5hZ2

This uses a negative lookahead, with the logic that if there is a closing square bracket before any opening square brackets, then the - that we tried to match is inside of brackets.

Leave a Comment