Saturday, January 4, 2025
HomeTechRegular Expression to Match a Line that Doesn't Contain a Word

Regular Expression to Match a Line that Doesn’t Contain a Word

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:

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

Explanation:

  1. ^: Asserts the position at the start of the line.
  2. (?!.*\bword\b): This is the negative lookahead. It asserts that, starting from the beginning of the line, the word word 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.
  3. .*: This matches the rest of the line after the negative lookahead.
See also  Object Class in Java

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 .*.
RELATED ARTICLES

Leave a Reply

- Advertisment -

Most Popular

Who is PVD Biggie? 

Celebrities Born in 1967

Who is Kaylee Hottle? 

Who is Jackie Christie?

Recent Comments