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.
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:
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 wordfoo..*: Matches any character (except line terminators) zero or more times.\b: Word boundary, ensuring thatfoois matched as a whole word and not as part of another word (likefoobar).
.*: Matches the rest of the line after confirming that the wordfoois not present.
Example:
Let's say you have the following text:
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:
Output:
Summary
^(?!.*\bword\b).*$: This regular expression matches any line that does not contain the specific wordword.^asserts the start of the line.(?!.*\bword\b)ensures that the wordworddoes 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.
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack 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.