Search code examples
regexparsingdelphiregex-lookarounds

regex - find multiline string that does not contain substring


I need to find certain chunks of code that are missing the raise keyword as follows:

These are the types of matches that I'm searching for

except
  FreeAndNil(result);
end;

While these should be ignored:

except
  FreeAndNil(result);
  raise;
end;

Bear in mind that between the except and end; keywords there may be any type or length of text.

I tried the following regex expression: except((?!raise).)*end; however it does not work on a multiline scenario.


Solution

  • An option matching the newlines could be matching all the lines between except and end by using a negative lookahead asserting that those lines do not start with either of except or end:

    \bexcept\s*\r?\n(?:(?!(?:except|[\t ]+raise;)$).*\r?\n)*end;
    

    In parts

    • \bexcept\s*\r?\n Match except, 0+ whitespace chars and a newline
    • (?: Non capturing group
      • (?! Negative lookahead, assert what is on the right is not
        • (?:except|[\t ]+raise;)$) Match either except or 1+ spaces or tabs and raise; followed by the end of the string.
      • ) Close lookahead
      • .*\r?\n Match the whole line followed by a newline
    • )* Repeat the non capturing group 0+ times
    • end; Match literally

    Regex demo