Regex Pattern Causes Catastrophic Backtracking In Edge Cases

Viewed 52

I have these two simple regex patterns to match urls that are from these stores, but they lead to catastrophic backtracking and a frozen browser when running on some string url with an edge case. This logic is running on thousands of random requests, so the chance of catastrophic backtracking is high. Does anyone have an idea of what could be wrong in the way I wrote this regex.

> ".*://.*.newegg.com/Product/Product.*"
> ".*://.*.gamestop.com*.*Product-Variation*.*productDetailsRedesign"
1 Answers

You have too many greedy dot patterns in the expressions. Try be a ted bit more verbose:

\w+://[^/]*\.newegg\.com/Product/Product\S*

The second pattern:

\w+://[^\s/]*\.gamestop\.com\S*?Product-Variation\S*?productDetailsRedesign

See proof #1 | proof #2.

Use \S*? to match any characters different from whitespace (as few as possible).

Escape the period characters as they are regex metacharacters.

Use [^...] negated character classes if you know there can be no such characters between two substrings in a match.

Related