To create a regular expression that matches a line that does not contain a specific word, you can use a negative lookahead. A negative lookahead asserts that a pattern is not followed by another pattern.
Here’s the regular expression:
Regular Expression:
Explanation:
^
: Asserts the position at the start of the line.(?!.*\bword\b)
: This is the negative lookahead. It asserts that, starting from the beginning of the line, the wordword
is not present anywhere in the line. The.*
matches any number of characters, and\b
ensures the word boundaries so it doesn’t match part of a larger word..*
: This matches the rest of the line after the negative lookahead.
Example:
- For a line that does not contain the word “apple”:
- Matches: “This is a test.”, “Bananas are yellow.”
- Does not match: “I like apple pie.”, “An apple a day keeps the doctor away.”
How It Works:
- The expression checks if the word “apple” appears anywhere on the line using the negative lookahead
(?!.*\bapple\b)
. - If “apple” is not present, it will match the whole line
.*
.