Ajedi32
Ajedi32

Reputation: 48368

Why does this regular expression cause my regex engine to hang?

Does anyone have any idea why this regular expression is causing my application to hang?

/^(?:((?:.+?)(?: of the )?)+) of the (?:(.+?)) (?:"(.+?)")$/

It hangs when I try to use it to match strings like this:

'description of the post "This is a Post"'

But it seems to happen pretty fast when I use it to match a shorter string like this: 'age of the person "Bob"'

Any ideas on why this is happening or how I can fix it?

Upvotes: 0

Views: 93

Answers (2)

Andrew Clark
Andrew Clark

Reputation: 208465

This is the result of catastrophic backtracking in your regular expression, the following portion of your regex is likely the culprit:

((?:.+?)(?: of the )?)+

You should try to refactor your regular expression any time you have nested repetition. In this case I think you can simplify that entire portion to .+ and have your regex behave the same way.

Upvotes: 2

Ankur
Ankur

Reputation: 12774

this might be because there are so many backtracking/grouping that it takes lot of time to parse a larger string.

As you can see in the demo: http://regex101.com/r/xC3dF0, the system is not able to parse the string due to large number of backtracking

Upvotes: 1

Related Questions