.Net Regular Expression Crashes aspnet_wp.exe
I was having the following problem and was wondering if anyone could understand why my .net worker process (aspnet_wp.exe) is crashing:
Dim pattern As String = "\{\{IF\(((?!\)}})(.))+,,,((\s)*(?!\)}})(.))+\)}}"
Dim mc As RegularExpressions.MatchCollection = Regex.Matches(txtContent.Text, pattern)
Works absolutely fine if a match is found, for example
<h3>Title</h3>
<p>Top paragraph.</p>
{{IF(1=2,,, <p></p>)}}
But if no match is found, it seems to nail my cpu and takes quite a long time, for example if the last bit is missing until the last two curly brakcets:
<h3>Title</h3>
<p>Top paragraph.</p>
{{IF(1=2,,, <p></p>}}
Is it too greedy that he searches forever !? Thank!
source to share
The problem is easily identified as "Catastrophic Rollback" .
Anytime you see "if a match exists, it works, if a match doesn't exist, it happens forever", you can be sure of the cause.
I suggest another regex that does less backtracking. Atomic grouping can help minimize the return steps:
Dim pattern As String = "\{\{IF\((?>(?:(?!,,,).)+),,,(?>(?:(?!\)\}\}).)+)\}\}"
Dim mc As RegularExpressions.MatchCollection = Regex.Matches(txtContent.Text, pattern)
Template (don't know if I'm taking whatever you need - add parentheses wherever you see fit):
\{\{IF\( # "{{IF("
(?>(?:(?!,,,).)+) # atomic group: any char up to the ",,,"
,,, # ",,,"
(?>(?:(?!\)\}\}).)+) # atomic group: any char up to the ")}}"
\)\}\} # ")}}"
source to share