Regex contains runaway part

Viewed 64

I'm building a Regex to parse some "filter strings". String which contains conditions which have to match, combined by "and" or "or" operators. For this I needed a regex which searches for matching brackets.¨

A filter string can look like this: (param2="def" or param2="ghj") and param1="abc"

It works as expected, but if I enter a typo, like a newer closing bracket, I receive an error for "Runaway Regular Expression"

The part of the regex which is looking for matching brackets: /\(((?:[^)(]+|\((?:[^)(]+|\([^)(]*\))*\))*)\)/

If I test this regex with following string (description=r\"Sending \[A-Z0-9]{8}\"), and if I add a opening bracket "(" anywhere inside, it's throwing the error.

Especially in JavaScript I'm not sure if there is a way to catch this error.

Regex Demo: https://regex101.com/r/eE6mX3/1

1 Answers

You need to re-write the pattern so that it matched:

  • a ( char
    • any chars other than ( and )
    • zero or more occurrences of
      • a ( char
      • any chars other than ( and )
      • a ) char
      • any chars other than ( and )

This way, the pattern will be as efficient as possible:

\([^()]*(?:\([^()]*\)[^()]*)*\)

See the regex demo.

Related