Jake
Jake

Reputation: 4234

Regular expression crashing Chrome when used as RegExp()

The regex in question is:

/\[quote\]((?:[^](?!\[quote\]))*?)\[\/quote\]/gi

The string I'm applying it to is

[quote]Level 10
[quote]Level 9
[quote]Level 8
[quote]Level 7
[quote]Level 6
[quote]Level 5
[quote]Level 4
[quote]Level 3
[quote]Level 2
[quote]Level 1[/quote]
Level 2[/quote]
Level 3[/quote]
Level 4[/quote]
Level 5[/quote]
Level 6[/quote]
Level 7[/quote]
Level 8[/quote]
Level 9[/quote]
Level 10[/quote]

When I create this using a RegExp(), like so, Chrome hangs:

new RegExp("\[quote\]((?:[^](?!\[quote\]))*?)\[\/quote\]", "gi")

It's also worth noting that this regex doesn't seem to parse correctly by some parsers, such as http://regexpal.com/.

My objective is to match the quotes from the inside out (starting with the innermost set and working my way out). Anyone have ideas for fixing the regex, or other ways to do what I'm trying to do?

Edit: If you want to see it behaving correctly, it does work here: http://regexr.com?34i3p

Upvotes: 1

Views: 706

Answers (1)

Kobi
Kobi

Reputation: 138017

When using a string to create a RegExp, you need to escape the slashes:

new RegExp("\\[quote\\]((?:[^](?!\\[quote\\]))*?)\\[\\/quote\\]", "i")

The slashes are ignored, so you end up with character classes like [quote].
It's possible failing to match these leads to catastrophic backtracking, though to be honest I don't quite see how.

Upvotes: 1

Related Questions