Skip to main content

How to Use a Negative Lookahead in a C# Regex

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

(?!...) checks that something does not come next, and uses up none of the text while it checks. ^(?!notes) means "at the start, as long as the text doesn't begin with notes".

Microsoft's reference: For the match to be successful, the input string must not match the regular expression pattern in subexpression, although the matched string is not included in the match result. In other words, a negative lookahead is a test, not part of the match.

Syntax​

Syntax
Regex.IsMatch(<text>, @"...(?!<subexpression>)...")
PartWhat it is
(?! and )A negative lookahead: the match fails if <subexpression> matches at this point
<subexpression>What must not come next, such as a word
Its positionIt's checked exactly where it stands in the pattern, and takes no characters

The Example​

A console app called NegativeLookahead checks four file names with two patterns: one for any .txt name, and one for .txt names that don't start with notes.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.

Step 1: Create a Console App​

Terminal
dotnet new console -n NegativeLookahead
cd NegativeLookahead
Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/NegativeLookahead/NegativeLookahead.csproj:
Determining projects to restore...
Restored /Users/you/source/NegativeLookahead/NegativeLookahead.csproj (in 48 ms).
Restore succeeded.

dotnet new console -n NegativeLookahead creates a folder named NegativeLookahead with a project file and a Program.cs, and cd moves into it. Everything this example uses is part of .NET, so there's no package to add. Open the folder in VS Code, or NegativeLookahead.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. First the names and the two patterns:

Program.cs (the patterns)
using System.Text.RegularExpressions;

string[] files = ["report.txt", "report.pdf", "notes.txt", "draft-notes.txt"];

// A file name that ends in .txt.
Regex txt = new(@"^[\w-]+\.txt$");

// The same, but (?!notes) rejects names that start with "notes" and uses up no characters.
Regex notNotes = new(@"^(?!notes)[\w-]+\.txt$");
  • ^[\w-]+\.txt$ is a name of letters, digits, _ and -, ending in .txt.
  • ^(?!notes) adds a test at the very start: what follows must not be notes.

Then check each name with both:

Program.cs (the check)
foreach (string file in files)
{
bool isText = txt.IsMatch(file);
bool isTextNotNotes = notNotes.IsMatch(file);
Console.WriteLine($"{file,-15} .txt: {isText,-5} not notes: {isTextNotNotes}");
}

Step 3: Run It​

Run it in VS Code's terminal, or press Ctrl+F5 in Visual Studio:

Terminal
dotnet run
Output
report.txt .txt: True not notes: True
report.pdf .txt: False not notes: False
notes.txt .txt: True not notes: False
draft-notes.txt .txt: True not notes: True

macOS-style terminal window titled Terminal — NegativeLookahead showing dotnet run: report.txt passes both patterns, report.pdf fails both, notes.txt is a txt name but is rejected by the lookahead, and draft-notes.txt passes both

notes.txt is a .txt name, but the lookahead rejected it. draft-notes.txt passed, because the lookahead only looks at the start of the name, and that one starts with draft.

The Complete File​

macOS-style code window titled Program.cs — NegativeLookahead showing four file names, a pattern for names ending in .txt, the same pattern with a negative lookahead for notes at the start, and a loop that prints both results for each name

Program.cs
using System.Text.RegularExpressions;

string[] files = ["report.txt", "report.pdf", "notes.txt", "draft-notes.txt"];

// A file name that ends in .txt.
Regex txt = new(@"^[\w-]+\.txt$");

// The same, but (?!notes) rejects names that start with "notes" and uses up no characters.
Regex notNotes = new(@"^(?!notes)[\w-]+\.txt$");

foreach (string file in files)
{
bool isText = txt.IsMatch(file);
bool isTextNotNotes = notNotes.IsMatch(file);
Console.WriteLine($"{file,-15} .txt: {isText,-5} not notes: {isTextNotNotes}");
}

Common Mistakes​

MistakeWhat happensDo this instead
Putting the lookahead in the wrong place^[\w-]+(?!notes)\.txt$ still matched notes.txt: at that point the next characters are .txt, not notesPut it where the text you want to rule out would begin
Expecting ^(?!notes) to rule out notes anywheredraft-notes.txt passedLook ahead over the whole name: ^(?!.*notes)[\w-]+\.txt$ rejected notes.txt and draft-notes.txt and accepted report.txt

FAQ​

Is there a positive lookahead?​

Yes, (?=...) requires what follows instead of ruling it out: \w+(?=\.txt) matched report in report.txt, without the .txt.

Where do lookaheads usually go?​

The reference: A zero-width negative lookahead assertion is typically used either at the beginning or at the end of a regular expression.

Conclusion​

(?!...) makes a match fail when the text at that point matches what's inside it, and it takes no characters of its own. Put it exactly where the unwanted text would start, or use .* inside it to look over everything that follows.

Additional Resources​