word
contain
match-line
regular-expression

Regular expression to match a line that doesn't contain a word

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

To create a regular expression that matches a line that doesn't contain a specific word, you can use a negative lookahead assertion. Here's how you can do it:

Basic Regex Structure

To match a line that does not contain a specific word (e.g., foo), you can use the following regular expression:

regex
^(?!.*\bfoo\b).*

Explanation:

  • ^: Asserts the position at the start of the line.
  • (?!.*\bfoo\b): This is a negative lookahead assertion that checks that the line does not contain the word foo.
    • .*: Matches any character (except line terminators) zero or more times.
    • \b: Word boundary, ensuring that foo is matched as a whole word and not as part of another word (like foobar).
  • .*: Matches the rest of the line after confirming that the word foo is not present.

Example:

Let's say you have the following text:

 
1This is a line with foo.
2This is a line without the forbidden word.
3Another line that doesn't mention it.
4But here is foo again.

The regex ^(?!.*\bfoo\b).* will match:

  • This is a line without the forbidden word.
  • Another line that doesn't mention it.

But it will not match lines that contain the word foo:

  • This is a line with foo.
  • But here is foo again.

Using in Code (JavaScript Example)

If you're using this in a JavaScript context, here’s how you could use it:

javascript
1const text = `
2This is a line with foo.
3This is a line without the forbidden word.
4Another line that doesn't mention it.
5But here is foo again.
6`;
7
8const lines = text.split('\n');
9const regex = /^(?!.*\bfoo\b).*/;
10
11const matchingLines = lines.filter(line => regex.test(line));
12
13console.log(matchingLines);

Output:

javascript
1[
2  'This is a line without the forbidden word.',
3  "Another line that doesn't mention it."
4]

Summary

  • ^(?!.*\bword\b).*$: This regular expression matches any line that does not contain the specific word word.
  • ^ asserts the start of the line.
  • (?!.*\bword\b) ensures that the word word does not appear in the line.
  • .* matches the rest of the line.

This pattern can be used in various programming languages and tools that support regular expressions, making it versatile for searching or filtering lines in text files, logs, and more.


Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions