views:

34453

answers:

3

I know it is possible to match for the word and using tools options reverse the match. (eg. by grep -v) However I want to know if it is possible using regular expressions to match lines which does not contain a specific word, say hede?

Input:

Hoho
Hihi
Haha
hede

# grep "Regex for do not contain hede" Input

Output:

Hoho
Hihi
Haha
+3  A: 

If you're just using it for grep, you can use grep -v hede to get all lines which do not contain hede.

ETA Oh, rereading the question, grep -v is probably what you meant by "tools options".

Athena
+2  A: 

Here's a good explanation of why it's not easy to negate an arbitrary regex. I have to agree with the other answers, though: if this is anything other than a hypothetical question, then a regex is not the right choice here.

jleedev
+59  A: 

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

^((?!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.

Bart Kiers
Perfect! Just used this!
George Edison