Regex – How to match all brackets that are not inside quotes


^ – Anchor to the start of the string. This is important because of what’s next.

(?> – atomic group. once matched, don’t backtrack.

".*" – Consume anything in quotes. Once consumed, the engine won’t backtrack for it

| – or

[^!{}] – match anything that isn’t the characters we’re interested in. These are still part of the atomic group, so anything consumed can’t be matched.

)* – Close the atomic group and match the entire group 0 or more times.

\K – reset the pattern. Throw away everything matched up until this point.

!{.*} – What you’re looking for.

So because we’re starting out anchored, we’re going to consume anything that is in quotes, or definitely isn’t what we want. It’s consumed in a way that won’t let the engine backtrack for it. Then once we get to what we’re looking for, we throw everything away. This means anything in quotes won’t be matched.


Thanks to @Nick posting the link to the other thread, I’ve found there’s a much simpler way to go about it that works with javascript:


".*" match anything in quotes, ungrouped

| or

(!{.*}) match what you’re looking for in group 1.

While technically you’re matching unwanted strings, you can filter out everything that doesn’t return a group 1, leaving you with what you’re looking for.

Leave a Comment