Maxim
Maxim

Reputation: 2128

Negative lookahead in singleline regex

I have following test string:

/// <exception cref="x"><paramref name="a"/> is null.</exception>
/// <exception cref="y"><paramref name="b"/> is null. -or-
/// </exception>dfjhhdfhdfkjhdkjdfhkdfjhdf -or-

It's a three-line string. So I've created regex with Singleline flag to capture new lines with dot. My regex is:

(<exception.+?>)(?<a>.+?)(?!<\/exception>)-or-

With this regex I expect to match only second line. But what I get is (visualized with regex101.com):

enter image description here

First two lines are matched and second group includes </exception> although I've specified negative lookahead (?!<\/exception>).

Why this happened? How can I match second line relying on presense of -or-?

Upvotes: 1

Views: 170

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521093

This might be overkill, but you could use a tempered dot to match the -or- without passing a closing tag:

<exception[^>]*>((?!</exception>).)*-or-

Demo

This regex pattern says to:

<exception[^>]*>      match an opening <exception> tag
((?!</exception>).)*  then match any content WITHOUT passing a closing </exception> tag
-or-                  match -or-

Upvotes: 1

Related Questions