Search code examples
c#regex

Regex match line with string AND without another string


There are tons of great answers on SO how to match a line that does not contain a line, or match until a string of characters.

I am trying to tweak these into a regex that matches lines with a specific word AND lacking a certain word.

An example line that I want to find:

var status = await _client.Get<Status>();

An example line that I don't want to find:

await _client.GetStream().WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);   

Thus, every line that starts with 'await' and does not specify 'ConfigureAwait' should be matched.

I've tried all kind of things, e.g. :

regex: await.*(?!Configure)

But whenever I use something like .* in the regex, it matches everything (including the ConfigureAwait part).

So how do I tell the regex parser to 'match anything BUT <...>'


Solution

  • Try: (?=^.*await)(?!^.+ConfigureAwait).+

    Explanation:

    (?=^.*await) - positive lookahead: assert what is following is: ^ beginning of a line, followed by one or more of any characters due to .+ and a word await, concisely: assert that there is await in a line

    (?!^.+ConfigureAwait) - negative lookahead: similairly to above, but negated :) assert that following line doesn't contain ConfigureAwait

    .+ - match one ore more of any character (except new line)

    Demo