regex – Regular expression to match a line that doesnt contain a word

regex – Regular expression to match a line that doesnt contain a word

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

^((?!hede).)*$

Non-capturing variant:

^(?:(?!:hede).)*$

The regex above will match any string, or line without a line break, not containing the (sub)string hede. 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):

/^((?!hede).)*$/s

or use it inline:

/(?s)^((?!hede).)*$/

(where the /.../ are the regex delimiters, i.e., not part of the pattern)

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

/^((?!hede)[sS])*$/

Explanation

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

regex – Regular expression to match a line that doesnt contain a word

Leave a Reply

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