Regular Expression: Match Line Not Containing a Specific Word

Here means to explain how to match lines not containing a specific word (e.g. codingrepo) using regular expression.

The notion that regex doesn’t support inverse matching is not entirely true. You can mimic this behavior by using negative look-arounds:

The regex above will match any string, or line without a line break, not containing the (sub) string codingrepo. As mentioned, this is not something regex is “good” at (or should do), but still, it is possible.

And if you need to match line break chars as well, use the DOT-ALL modifier (the trailing s in the following pattern):

or use it inline:

(where the /…/ are the regex delimiters, ie, not part of the pattern)

If the DOT-ALL modifier is not available, you can mimic the same behavior with the character class [\s\S]:


Explanation

A string is just a list of n characters. Before, and after each character, there’s an empty string. So a list of n characters will have n+1 empty strings. Consider the string ABcodingrepoCD:

+–+—+–+—+–+—+–+—+–+—+–+—+–+—+–+—+–+–+–+
S = |e1| A |e2| B |e3| h |e4| e |e5| d |e6| e |e7| C |e8| D |e9|
+–+—+–+—+–+—+–+—+–+—+–+—+–+—+–+—+–+–+–+

index 0 1 2 3 4 5 6 7

where the e’s are the empty strings. The regex (?!codingrepo). looks ahead to see if there’s no substring codingrepo to be seen, and if that is the case (so something else is seen), then the . (dot) will match any character except a line break. Look-arounds are also called zero-width-assertions because they don’t consume any characters. They only assert/validate something.

So, in my example, every empty string is first validated to see if there’s no codingrepo up ahead, before a character is consumed by the .(dot). The regex (?!codingrepo). will do that only once, so it is wrapped in a group, and repeated zero or more times: ((?!codingrepo).)*. Finally, the start- and end-of-input are anchored to make sure the entire input is consumed: ^((?!codingrepo).)*$

As you can see, the input ABcodingrepoCD will fail because on e3, the regex (?!codingrepo) fails (there is “codingrepo” up ahead!).


Summary for ^((?!codingrepo).)*$

^ beginning of the string
( group and capture to \1 (0 or more times (matching the most amount possible))
(?! look ahead to see if there is not
codingrepo our specific string to exclude
) end of look-ahead
. any character except \n
)* end of \1 (NOTE: because you are using a quantifier on this capture, only the LAST repetition of the captured pattern will be stored in \1)
$ before an optional \n, and the end of the string

Resource: Stackoverflow

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA