简体   繁体   中英

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM