By knaser

2009-01-02 07:30:16 8 Comments

I know it's possible to match a word and then reverse the matches using other tools (e.g. grep -v). However, is it possible to match lines that do not contain a specific word, e.g. hede, using a regular expression?




grep "<Regex for 'doesn't contain hede'>" input

Desired output:



@Pedro Gimeno 2016-12-06 21:24:15

Since no one else has given a direct answer to the question that was asked, I'll do it.

The answer is that with POSIX grep, it's impossible to literally satisfy this request:

grep "<Regex for 'doesn't contain hede'>" input

The reason is that POSIX grep is only required to work with Basic Regular Expressions, which are simply not powerful enough for accomplishing that task (they are not capable of parsing regular languages, because of lack of alternation and parentheses).

However, GNU grep implements extensions that allow it. In particular, \| is the alternation operator in GNU's implementation of BREs, and \( and \) are the parentheses. If your regular expression engine supports alternation, negative bracket expressions, parentheses and the Kleene star, and is able to anchor to the beginning and end of the string, that's all you need for this approach. Note however that negative sets [^ ... ] are very convenient in addition to those, because otherwise, you need to replace them with an expression of the form (a|b|c| ... ) that lists every character that is not in the set, which is extremely tedious and overly long, even more so if the whole character set is Unicode.

With GNU grep, the answer would be something like:

grep "^\([^h]\|h\(h\|eh\|edh\)*\([^eh]\|e[^dh]\|ed[^eh]\)\)*\(\|h\(h\|eh\|edh\)*\(\|e\|ed\)\)$" input

(found with Grail and some further optimizations made by hand).

You can also use a tool that implements Extended Regular Expressions, like egrep, to get rid of the backslashes:

egrep "^([^h]|h(h|eh|edh)*([^eh]|e[^dh]|ed[^eh]))*(|h(h|eh|edh)*(|e|ed))$" input

Here's a script to test it (note it generates a file testinput.txt in the current directory):


# First four lines as in OP's testcase.
cat > testinput.txt <<EOF

diff -s -u <(grep -v hede testinput.txt) <(grep "$REGEX" testinput.txt)

In my system it prints:

Files /dev/fd/63 and /dev/fd/62 are identical

as expected.

For those interested in the details, the technique employed is to convert the regular expression that matches the word into a finite automaton, then invert the automaton by changing every acceptance state to non-acceptance and vice versa, and then converting the resulting FA back to a regular expression.

Finally, as everyone has noted, if your regular expression engine supports negative lookahead, that simplifies the task a lot. For example, with GNU grep:

grep -P '^((?!hede).)*$' input

Update: I have recently found Kendall Hopkins' excellent FormalTheory library, written in PHP, which provides a functionality similar to Grail. Using it, and a simplifier written by myself, I've been able to write an online generator of negative regular expressions given an input phrase (only alphanumeric and space characters currently supported):

For hede it outputs:


which is equivalent to the above.

@Emma 2019-08-01 02:36:22

Another option is that to add a positive look-ahead and check if hehe is anywhere in the input line, then we would negate that, with an expression similar to:


with word boundaries.

The expression is explained on the top right panel of, if you wish to explore/simplify/modify it, and in this link, you can watch how it would match against some sample inputs, if you like.

RegEx Circuit visualizes regular expressions:

enter image description here

@cloudhopperpilot 2019-03-26 12:21:23

^((?!hede).)*$ is an elegant solution, except since it consumes characters you won't be able to combine it with other criteria. For instance, say you wanted to check for the non-presence of "hede" and the presence of "haha." This solution would work because it won't consume characters:


@staafl 2018-11-24 18:26:48

An, in my opinon, more readable variant of the top answer:


Basically, "match at the beginning of the line if and only if it does not have 'hede' in it" - so the requirement translated almost directly into regex.

Of course, it's possible to have multiple failure requirements:


Details: The ^ anchor ensures the regex engine doesn't retry the match at every location in the string, which would match every string.

The ^ anchor in the beginning is meant to represent the beginning of the line. The grep tool matches each line one at a time, in contexts where you're working with a multiline string, you can use the "m" flag:

/^(?!.*hede)/m # JavaScript syntax


(?m)^(?!.*hede) # Inline flag

@Peter Parada 2019-07-11 16:50:52

Excellent example with multiple negation.

@Z. Khullah 2019-08-20 19:33:04

One difference from top answer is that this does not match anything, and that matches the whole line if without "hede"

@Roy Tinker 2013-01-03 21:22:09

If you want the regex test to only fail if the entire string matches, the following will work:


e.g. -- If you want to allow all values except "foo" (i.e. "foofoo", "barfoo", and "foobar" will pass, but "foo" will fail), use: ^(?!foo$).*

Of course, if you're checking for exact equality, a better general solution in this case is to check for string equality, i.e.

myStr !== 'foo'

You could even put the negation outside the test if you need any regex features (here, case insensitivity and range matching):


The regex solution at the top of this answer may be helpful, however, in situations where a positive regex test is required (perhaps by an API).

@eagor 2017-05-12 09:45:27

what about trailing whitespaces? Eg, if I want test to fail with string " hede "?

@Roy Tinker 2017-05-12 21:07:42

@eagor the \s directive matches a single whitespace character

@eagor 2017-05-13 19:22:41

thanks, but I didn't manage to update the regex to make this work.

@Roy Tinker 2017-05-15 17:33:04

@eagor: ^(?!\s*hede\s*$).*

@Donald 2018-07-09 17:08:32

With ConyEdit, you can use the command line !/hede/ to get lines that do not contain the regex matching, or use the command line cc.dl /hede/ to delete lines that contain the regex matching. They have the same result.

@Casimir et Hippolyte 2013-04-14 03:04:42

with this, you avoid to test a lookahead on each positions:


equivalent to (for .net):


Old answer:


@Alan Moore 2013-04-14 05:26:42

Good point; I'm surprised nobody mentioned this approach before. However, that particular regex is prone to catastrophic backtracking when applied to text that doesn't match. Here's how I would do it: /^[^h]*(?:h+(?!ede)[^h]*)*$/

@Alan Moore 2013-04-15 15:17:58

...or you can just make all the quantifiers possessive. ;)

@ridgerunner 2013-12-20 03:08:40

@Alan Moore - I'm surprised too. I saw your comment (and best regex in the pile) here only after posting this same pattern in an answer below.

@Qtax 2014-02-20 13:10:10

@ridgerunner, doesn't have to be the best tho. I've seen benchmarks where the top answer performs better. (I was surprised about that tho.)

@BrunoFacca 2018-04-25 18:15:32

Maybe you'll find this on Google while trying to write a regex that is able to match segments of a line (as opposed to entire lines) which do not contain a substring. Tooke me a while to figure out, so I'll share:

Given a string: <span class="good">bar</span><span class="bad">foo</span><span class="ugly">baz</span>

I want to match <span> tags which do not contain the substring "bad".

/<span(?:(?!bad).)*?> will match <span class=\"good\"> and <span class=\"ugly\">.

Notice that there are two sets (layers) of parentheses:

  • The innermost one is for the negative lookahead (it is not a capture group)
  • The outermost was interpreted by Ruby as capture group but we don't want it to be a capture group, so I added ?: at it's beginning and it is no longer interpreted as a capture group.

Demo in Ruby:

s = '<span class="good">bar</span><span class="bad">foo</span><span class="ugly">baz</span>'
# => ["<span class=\"good\">", "<span class=\"ugly\">"]

@akim 2015-08-05 07:02:36

FWIW, since regular languages (aka rational languages) are closed under complementation, it's always possible to find a regular expression (aka rational expression) that negates another expression. But not many tools implement this.

Vcsn supports this operator (which it denotes {c}, postfix).

You first define the type of your expressions: labels are letter (lal_char) to pick from a to z for instance (defining the alphabet when working with complementation is, of course, very important), and the "value" computed for each word is just a Boolean: true the word is accepted, false, rejected.

In Python:

In [5]: import vcsn
        c = vcsn.context('lal_char(a-z), b')
Out[5]: {a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z} β†’ 𝔹

then you enter your expression:

In [6]: e = c.expression('(hede){c}'); e
Out[6]: (hede)^c

convert this expression to an automaton:

In [7]: a = e.automaton(); a

The corresponding automaton

finally, convert this automaton back to a simple expression.

In [8]: print(a.expression())

where + is usually denoted |, \e denotes the empty word, and [^] is usually written . (any character). So, with a bit of rewriting ()|h(ed?)?|([^h]|h([^e]|e([^d]|d([^e]|e.)))).*.

You can see this example here, and try Vcsn online there.

@reinierpost 2015-11-08 23:43:24

True, but ugly, and only doable for small character sets. You don't want to do this with Unicode strings :-)

@Peter K 2016-11-18 15:09:05

There are more tools that allow it, one of the most impressive being Ragel. There it would be written as (any* - ('hehe' any*)) for start-aligned match or (any* -- ('hehe' any*)) for unaligned.

@Peter K 2016-11-18 15:39:42

@reinierpost: why is it ugly and what's the problem with unicode? I can't agree on both. (I have no experience with vcsn, but have with DFA).

@Pedro Gimeno 2016-12-06 23:18:38

The regexp ()|h(ed?)?|([^h]|h([^e]|e([^d]|d([^e]|e.)))).* didn't work for me using egrep. It matches hede. I also tried anchoring it to the beginning and end, and it still didn't work.

@akim 2016-12-08 09:03:41

@PedroGimeno When you anchored, you made sure to put this regex in parens first? Otherwise the precedences between anchors and | won't play nicely. '^(()|h(ed?)?|([^h]|h([^e]|e([^d]|d([^e]|e.)))).*)$'.

@Pedro Gimeno 2016-12-09 15:45:41

@akim That seemed to be the problem, thanks and sorry (see my answer for a full substring match). And forgot to say, the graph doesn't have [^d] anywhere. I suspect that's a mistake.

@akim 2016-12-11 07:02:30

@PedroGimeno Thanks for pointing this out. When I first answered I read incorrectly and thought that hehe was to reject. I fixed the text, but forgot to fix the snapshot.

@Pedro Gimeno 2019-01-29 00:05:37

I think it's worth remarking that this method is for matching lines that are not the word 'hede', rather than lines than don't contain the word 'hede' which is what the OP asked for. See my answer for the latter.

@Jessica 2014-05-10 16:36:11




^the 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,

hede your string,

) 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

@Damodar Bashyal 2015-08-11 02:07:31

awesome that worked for me in sublime text 2 using multiple words '^((?!DSAU_PW8882WEB2|DSAU_PW8884WEB2|DSAU_PW8884WEB).)*$'

@forresthopkinsa 2017-06-12 16:19:18

@DamodarBashyal I know I'm pretty late here, but you could totally remove the second term there and you would get the exact same results

@jaytea 2017-10-11 10:12:31

How to use PCRE's backtracking control verbs to match a line not containing a word

Here's a method that I haven't seen used before:


How it works

First, it tries to find "hede" somewhere in the line. If successful, at this point, (*COMMIT) tells the engine to, not only not backtrack in the event of a failure, but also not to attempt any further matching in that case. Then, we try to match something that cannot possibly match (in this case, ^).

If a line does not contain "hede" then the second alternative, an empty subpattern, successfully matches the subject string.

This method is no more efficient than a negative lookahead, but I figured I'd just throw it on here in case someone finds it nifty and finds a use for it for other, more interesting applications.

@Bart Kiers 2009-01-02 09:55:05

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 '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):


or use it inline:


(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 [\s\S]:



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 "ABhedeCD":

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 (?!hede). looks ahead to see if there's no substring "hede" 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 "hede" up ahead, before a character is consumed by the . (dot). The regex (?!hede). will do that only once, so it is wrapped in a group, and repeated zero or more times: ((?!hede).)*. Finally, the start- and end-of-input are anchored to make sure the entire input is consumed: ^((?!hede).)*$

As you can see, the input "ABhedeCD" will fail because on e3, the regex (?!hede) fails (there is "hede" up ahead!).

@Archimaredes 2016-03-03 16:09:36

I would not go so far as to say that this is something regex is bad at. The convenience of this solution is pretty obvious and the performance hit compared to a programmatic search is often going to be unimportant.

@Peter K 2016-11-18 15:03:19

Strictly speaking negative loook-ahead makes you regular expression not-regular.

@Bart Kiers 2016-11-18 15:08:29

@PeterK, sure, but this is SO, not MathOverflow or CS-Stackexchange. People asking a question here are generally looking for a practical answer. Most libraries or tools (like grep, which the OP mentions) with regex-support all have features that mke them non-regular in a theoretical sense.

@Peter K 2016-11-18 15:33:07

@Bart Kiers, no offense to you answer, just this abuse of terminology irritates me a bit. The really confusing part here is that regular expressions in the strict sense can very much do what OP wants, but the common language to write them does not allow it, which leads to (mathematically ugly) workarounds like look-aheads. Please see this answer below and my comment there for (theoretically aligned) proper way of doing it. Needless to say it works faster on large inputs.

@baldrs 2016-11-24 11:58:11

In case you ever wondered how to do this in vim: ^\(\(hede\)\@!.\)*$

@intcreator 2017-06-08 23:11:23

This answer worked better for me. Can you explain the difference between ^((?!hede).)*$ and ^(?!hede).*$?

@Bart Kiers 2017-12-05 20:34:45

@Z.Khullah You're missing the m flag. Adding it in your regex didn't do the trick, but creating a new test with m did work on Regexr: In short: it's a bug in Regexr.

@emte 2018-01-03 12:22:13

Hi, can you please tell me how to do this for re2 from google?

@alpha_989 2018-03-26 17:32:09

Lookbacks/lookarounds are only supported in pcre Perhaps a disclaimer should be added.

@Bart Kiers 2018-03-26 18:04:27

@alpha_989 true, but I don't think a disclaimer is needed. This is SO, not Math Overflow or CS-SE, and nearly all popular programming languages with regex-support are PCRE (is close to it).

@SL5net 2019-01-11 20:19:59

same with word boundaries: ^((?!\bhede\b).)*$

@JackPRead 2019-01-15 10:52:52

Why are so many answers saying ^((?!hede).)*$ ? Is it not more efficient to use ^(?!.*hede).*$ ? It does the same thing but in fewer steps.

@deeenes 2019-01-22 16:08:54

A little extension, I know it was not in the question but might be useful. What if you want to filter more than one words, the same time match for these words separately, and remove spaces and line breaks in addition. I tested it in Python: import re; exp = re.compile(r'(?!\s)(?:AND|OR|NOT|\(|\)|(?:(?!OR|AND|NOT|\s{2‌​:})(?:[-\w: ]))+)(?<!\s)'); exp.findall('foobar AND (foo loves bar OR NOT bla bla)') results: ['foobar', 'AND', '(', 'foo loves bar', 'OR', 'NOT', 'bla bla', ')']

@martinmmps 2019-12-12 12:42:01

Would you be able to make a regex that doesn't contain a symbol like '@'?

@aelor 2017-03-23 13:42:32

Since the introduction of ruby-2.4.1, we can use the new Absent Operator in Ruby’s Regular Expressions

from the official doc

(?~abc) matches: "", "ab", "aab", "cccc", etc.
It doesn't match: "abc", "aabc", "ccccabc", etc.

Thus, in your case ^(?~hede)$ does the job for you

2.4.1 :016 > ["hoho", "hihi", "haha", "hede"].select{|s| /^(?~hede)$/.match(s)}
 => ["hoho", "hihi", "haha"]

@Daniel Nyamasyo 2016-12-21 04:55:17

The below function will help you get your desired output

      function removePrepositions($text){


            if( count($propositions) > 0 ) {
                foreach($propositions as $exceptionPhrase) {
                    $text = preg_replace($exceptionPhrase, '', trim($text));

            $retval = trim($text);

        return $retval;


@JohnP2 2016-09-13 13:52:13

A simpler solution is to use the not operator !

Your if statement will need to match "contains" and not match "excludes".

var contains = /abc/;
var excludes =/hede/;

if(string.match(contains) && !(string.match(excludes))){  //proceed...

I believe the designers of RegEx anticipated the use of not operators.

@andrew pate 2015-02-18 11:45:28

It may be more maintainable to two regexes in your code, one to do the first match, and then if it matches run the second regex to check for outlier cases you wish to block for example ^.*(hede).* then have appropriate logic in your code.

OK, I admit this is not really an answer to the posted question posted and it may also use slightly more processing than a single regex. But for developers who came here looking for a fast emergency fix for an outlier case then this solution should not be overlooked.

@ikegami 2016-08-23 00:03:27

Aforementioned (?:(?!hede).)* is great because it can be anchored.

^(?:(?!hede).)*$               # A line without hede

foo(?:(?!hede).)*bar           # foo followed by bar, without hede between them

But the following would suffice in this case:

^(?!.*hede)                    # A line without hede

This simplification is ready to have "AND" clauses added:

^(?!.*hede)(?=.*foo)(?=.*bar)   # A line with foo and bar, but without hede
^(?!.*hede)(?=.*foo).*bar       # Same

@Avinash Raj 2014-10-09 07:00:55

Through PCRE verb (*SKIP)(*F)


This would completely skips the line which contains the exact string hede and matches all the remaining lines.


Execution of the parts:

Let us consider the above regex by splitting it into two parts.

  1. Part before the | symbol. Part shouldn't be matched.

  2. Part after the | symbol. Part should be matched.



Regex engine will start its execution from the first part.



  • ^ Asserts that we are at the start.
  • hede Matches the string hede
  • $ Asserts that we are at the line end.

So the line which contains the string hede would be matched. Once the regex engine sees the following (*SKIP)(*F) (Note: You could write (*F) as (*FAIL)) verb, it skips and make the match to fail. | called alteration or logical OR operator added next to the PCRE verb which inturn matches all the boundaries exists between each and every character on all the lines except the line contains the exact string hede. See the demo here. That is, it tries to match the characters from the remaining string. Now the regex in the second part would be executed.




  • ^ Asserts that we are at the start. ie, it matches all the line starts except the one in the hede line. See the demo here.
  • .* In the Multiline mode, . would match any character except newline or carriage return characters. And * would repeat the previous character zero or more times. So .* would match the whole line. See the demo here.

    Hey why you added .* instead of .+ ?

    Because .* would match a blank line but .+ won't match a blank. We want to match all the lines except hede , there may be a possibility of blank lines also in the input . so you must use .* instead of .+ . .+ would repeat the previous character one or more times. See .* matches a blank line here.

  • $ End of the line anchor is not necessary here.

@Falco 2014-08-13 14:58:27


I decided to evaluate some of the presented Options and compare their performance, as well as use some new Features. Benchmarking on .NET Regex Engine:

Benchmark Text:

The first 7 lines should not match, since they contain the searched Expression, while the lower 7 lines should match!

Regex Hero is a real-time online Silverlight Regular Expression Tester.
XRegex Hero is a real-time online Silverlight Regular Expression Tester.
Regex HeroRegex HeroRegex HeroRegex HeroRegex Hero is a real-time online Silverlight Regular Expression Tester.
Regex Her Regex Her Regex Her Regex Her Regex Her Regex Her Regex Hero is a real-time online Silverlight Regular Expression Tester.
Regex Her is a real-time online Silverlight Regular Expression Tester.Regex Hero
egex Hero egex Hero egex Hero egex Hero egex Hero egex Hero Regex Hero is a real-time online Silverlight Regular Expression Tester.

Regex Her
egex Hero
egex Hero is a real-time online Silverlight Regular Expression Tester.
Regex Her is a real-time online Silverlight Regular Expression Tester.
Regex Her Regex Her Regex Her Regex Her Regex Her Regex Her is a real-time online Silverlight Regular Expression Tester.
Nobody is a real-time online Silverlight Regular Expression Tester.
Regex Her o egex Hero Regex  Hero Reg ex Hero is a real-time online Silverlight Regular Expression Tester.


Results are Iterations per second as the median of 3 runs - Bigger Number = Better

01: ^((?!Regex Hero).)*$                    3.914   // Accepted Answer
02: ^(?:(?!Regex Hero).)*$                  5.034   // With Non-Capturing group
03: ^(?>[^R]+|R(?!egex Hero))*$             6.137   // Lookahead only on the right first letter
04: ^(?>(?:.*?Regex Hero)?)^.*$             7.426   // Match the word and check if you're still at linestart
05: ^(?(?=.*?Regex Hero)(?#fail)|.*)$       7.371   // Logic Branch: Find Regex Hero? match nothing, else anything

P1: ^(?(?=.*?Regex Hero)(*FAIL)|(*ACCEPT))  ?????   // Logic Branch in Perl - Quick FAIL
P2: .*?Regex Hero(*COMMIT)(*FAIL)|(*ACCEPT) ?????   // Direct COMMIT & FAIL in Perl

Since .NET doesn't support action Verbs (*FAIL, etc.) I couldn't test the solutions P1 and P2.


I tried to test most proposed solutions, some Optimizations are possible for certain words. For Example if the First two letters of the search string are not the Same, answer 03 can be expanded to ^(?>[^R]+|R+(?!egex Hero))*$ resulting in a small performance gain.

But the overall most readable and performance-wise fastest solution seems to be 05 using a conditional statement or 04 with the possesive quantifier. I think the Perl solutions should be even faster and more easily readable.

@ikegami 2016-08-23 00:07:23

You should time ^(?!.*hede) too. /// Also, it's probably better to rank the expressions for the matching corpus and the non-matching corpus separately because it's usually a case that most line match or most lines don't.

@amobiz 2014-07-14 18:21:55

With negative lookahead, regular expression can match something not contains specific pattern. This is answered and explained by Bart Kiers. Great explanation!

However, with Bart Kiers' answer, the lookahead part will test 1 to 4 characters ahead while matching any single character. We can avoid this and let the lookahead part check out the whole text, ensure there is no 'hede', and then the normal part (.*) can eat the whole text all at one time.

Here is the improved regex:


Note the (*?) lazy quantifier in the negative lookahead part is optional, you can use (*) greedy quantifier instead, depending on your data: if 'hede' does present and in the beginning half of the text, the lazy quantifier can be faster; otherwise, the greedy quantifier be faster. However if 'hede' does not present, both would be equal slow.

Here is the demo code.

For more information about lookahead, please check out the great article: Mastering Lookahead and Lookbehind.

Also, please check out RegexGen.js, a JavaScript Regular Expression Generator that helps to construct complex regular expressions. With RegexGen.js, you can construct the regex in a more readable way:

var _ = regexGen;

var regex = _(
    _.anything().notContains(       // match anything that not contains:
        _.anything().lazy(), 'hede' //   zero or more chars that followed by 'hede',
                                    //   i.e., anything contains 'hede'

@S.Serpooshan 2017-03-01 07:20:19

so to simply check if given string does not contain str1 and str2: ^(?!.*(str1|str2)).*$

@amobiz 2017-03-02 09:59:57

Yes, or you can use lazy quantifier: ^(?!.*?(?:str1|str2)).*$, depending on your data. Added the ?: since we don't need to capture it.

@user5389726598465 2017-07-23 09:06:13

This is by far the best answer by a factor of 10xms. If you added your jsfiddle code and results onto the answer people might notice it. I wonder why the lazy version is faster than the greedy version when there is no hede. Shouldn't they take the same amount of time?

@amobiz 2017-08-03 03:50:51

Yes, they take the same amount of time since they both tests the whole text.

@Kaz 2014-06-25 01:23:45

The TXR Language supports regex negation.

$ txr -c '@(repeat)
@{nothede /~hede/}
@(do (put-line nothede))
@(end)'  Input

A more complicated example: match all lines that start with a and end with z, but do not contain the substring hede:

$ txr -c '@(repeat)
@{nothede /a.*z&~.*hede.*/}
@(do (put-line nothede))
@(end)' -
az         <- echoed
abcz       <- echoed
abhederz   <- not echoed; contains hede
ahedez     <- not echoed; contains hede
ace        <- not echoed; does not end in z
ahedz      <- echoed

Regex negation is not particularly useful on its own but when you also have intersection, things get interesting, since you have a full set of boolean set operations: you can express "the set which matches this, except for things which match that".

@Wiktor StribiΕΌew 2018-02-19 07:30:27

Note that it is also the solution for ElasticSearch Lucene based regex.

@diyism 2012-03-23 07:24:34

If you want to match a character to negate a word similar to negate character class:

For example, a string:

$str="aaa        bbb4      aaa     bbb7";

Do not use:

preg_match('/aaa[^bbb]+?bbb7/s', $str, $matches);


preg_match('/aaa(?:(?!bbb).)+?bbb7/s', $str, $matches);

Notice "(?!bbb)." is neither lookbehind nor lookahead, it's lookcurrent, for example:

"(?=abc)abcde", "(?!abc)abcde"

@Didier L 2012-05-21 16:35:40

There is no "lookcurrent" in perl regexp's. This is truly a negative lookahead (prefix (?!). Positive lookahead's prefix would be (?= while the corresponding lookbehind prefixes would be (?<! and (?<= respectively. A lookahead means that you read the next characters (hence β€œahead”) without consuming them. A lookbehind means that you check characters that have already been consumed.

@ridgerunner 2013-12-20 03:03:57

Here's how I'd do it:


Accurate and more efficient than the other answers. It implements Friedl's "unrolling-the-loop" efficiency technique and requires much less backtracking.

@JoshuaDavid 2011-03-17 04:21:26

Note that the solution to does not start with β€œhede”:


is generally much more efficient than the solution to does not contain β€œhede”:


The former checks for β€œhede” only at the input string’s first position, rather than at every position.

@Samih A 2015-05-10 10:42:31

Thanks, I used it to validate that the string dosn't contain squence of digits ^((?!\d{5,}).)*

@Alex 2015-06-26 10:34:16

^((?!hede).)*$ worked for me using the jQuery DataTable plugin to exclude a string from the dataset

@Aleks Ya 2015-10-18 21:33:02

Hello! I can't compose does not end with "hede" regex. Can you help with it?

@Nyerguds 2016-05-04 10:42:45

@AleksYa: just use the "contain" version, and include the end anchor into the search string: change the string to "not match" from "hede" to "hede$"

@doubleDown 2017-02-06 06:09:08

To match lines that does not end with "hede", one way is to use ^.*(?!hede).{4}. The number in braces should match the length of non-matching text you want (e.g. "hede" is length 4).

@carinlynchin 2017-07-14 23:29:10

I really don't get the double parenthesis... didn't understand the explanation above either.. So the first set says "make sure this doesn't exist ahead." but what is the second set for?

@carinlynchin 2017-07-14 23:40:59

for example...: ^(?!override)_*labor_cost --> only matches "labor_cost" of the following tests..... [default_labor_cost, testing_override, labor_cost, override_labor_cost]. Based on explanations above it seems I should get anything with an optional _ followed by labor_cost... so I should have two that pass, but only one is.

@thisismydesign 2017-09-14 16:53:33

@AleksYa: the does not end version could be done using negative lookbehind as: (.*)(?<!hede)$. @Nyerguds' version would work as well but completely misses the point on performance the answer mentions.

@JackPRead 2019-01-15 10:53:41

Why are so many answers saying ^((?!hede).)*$ ? Is it not more efficient to use ^(?!.*hede).*$ ? It does the same thing but in fewer steps

@Kevin Fegan 2013-04-26 22:28:37

The OP did not specify or Tag the post to indicate the context (programming language, editor, tool) the Regex will be used within.

For me, I sometimes need to do this while editing a file using Textpad.

Textpad supports some Regex, but does not support lookahead or lookbehind, so it takes a few steps.

If I am looking to retain all lines that Do NOT contain the string hede, I would do it like this:

1. Search/replace the entire file to add a unique "Tag" to the beginning of each line containing any text.

    Search string:^(.)  
    Replace string:<@#-unique-#@>\1  

2. Delete all lines that contain the string hede (replacement string is empty):

    Search string:<@#-unique-#@>.*hede.*\n  
    Replace string:<nothing>  

3. At this point, all remaining lines Do NOT contain the string hede. Remove the unique "Tag" from all lines (replacement string is empty):

    Search string:<@#-unique-#@>
    Replace string:<nothing>  

Now you have the original text with all lines containing the string hede removed.

If I am looking to Do Something Else to only lines that Do NOT contain the string hede, I would do it like this:

1. Search/replace the entire file to add a unique "Tag" to the beginning of each line containing any text.

    Search string:^(.)  
    Replace string:<@#-unique-#@>\1  

2. For all lines that contain the string hede, remove the unique "Tag":

    Search string:<@#-unique-#@>(.*hede)
    Replace string:\1  

3. At this point, all lines that begin with the unique "Tag", Do NOT contain the string hede. I can now do my Something Else to only those lines.

4. When I am done, I remove the unique "Tag" from all lines (replacement string is empty):

    Search string:<@#-unique-#@>
    Replace string:<nothing>  

@Hades32 2011-09-02 15:53:15

The given answers are perfectly fine, just an academic point:

Regular Expressions in the meaning of theoretical computer sciences ARE NOT ABLE do it like this. For them it had to look something like this:


This only does a FULL match. Doing it for sub-matches would even be more awkward.

@Steve-o 2014-02-19 17:25:48

Important to note this only uses basic POSIX.2 regular expressions and thus whilst terse is more portable for when PCRE is not available.

@ThomasMcLeod 2014-03-22 21:36:09

I agree. Many if not most regular expressions are not regular languages and could not be recognized by a finite automata.

@James Haigh 2014-06-13 16:54:33

@ThomasMcLeod, Hades32: Is it within the realms of any possible regular language to be able to say β€˜not’ and β€˜and’ as well as the β€˜or’ of an expression such as β€˜(hede|Hihi)’? (This maybe a question for CS.)

@James Haigh 2014-06-13 17:04:37

@JohnAllen: ME!!! …Well, not the actual regex but the academic reference, which also relates closely to computational complexity; PCREs fundamentally can not guarantee the same efficiency as POSIX regular expressions.

@ThomasMcLeod 2014-06-13 19:50:42

@JamesHaigh, not <string> is definitely regular but does and make sense? Ask a new question and notify me in a comment and I'll try to answer it.

@Falco 2014-08-13 12:57:05

Sorry -this answer just doesn't work, it will match hhehe and even match hehe partially (the second half)

@Dukeling 2015-07-13 18:59:10

This can be syntactically simplified to ^([^h].*|h([^e].*)?|he([^h].*)?|heh([^e].*)?|hehe.+)$ or ^(([^h]|h[^e]|he[^h]|heh[^e]|hehe.).*|h|he|heh)$.

@Pedro Gimeno 2018-01-29 21:59:54

See my answer for how to do it for submatches too. As for inverting a RE, the inverse always exists without needing extra operators. Grail has a tool to find it, the one I used in my answer.

@kiwalk 2011-02-23 14:00:23

Not regex, but I've found it logical and useful to use serial greps with pipe to eliminate noise.

eg. search an apache config file without all the comments-

grep -v '\#' /opt/lampp/etc/httpd.conf      # this gives all the non-comment lines


grep -v '\#' /opt/lampp/etc/httpd.conf |  grep -i dir

The logic of serial grep's is (not a comment) and (matches dir)

@Angel.King.47 2011-07-12 15:27:15

I think he is asking for the regex version of the grep -v

@Xavi Montero 2013-03-01 19:54:47

This is dangerous. Also misses lines like good_stuff #comment_stuff

@Josh Lee 2009-01-02 08:03:06

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.

@FGM 2012-08-07 12:21:12

Some tools, and specifically mysqldumpslow, only offer this way to filter data, so in such a case, finding a regex to do this is the best solution apart from rewriting the tool (various patches for this have not been included by MySQL AB / Sun / Oracle.

@Henno Vermeulen 2013-10-18 14:43:00

Exactly analagous to my situation. Velocity template engine uses regular expressions to decide when to apply a transformation (escape html) and I want it to always work EXCEPT in one situation.

@kingfrito_5005 2016-10-20 18:32:10

What alternative is there? Ive never encountered anything that could do precise string matching besides regex. If OP is using a programming language, there may be other tools available, but if he/she is using not writing code, there probably isnt any other choice.

@LarsH 2016-12-05 16:11:39

One of many non-hypothetical scenarios where a regex is the best available choice: I'm in an IDE (Android Studio) that shows log output, and the only filtering tools provided are: plain strings, and regex. Trying to do this with plain strings would be a complete fail.

@Athena 2009-01-02 07:41:22

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".

@Olivier Lalonde 2014-05-05 22:08:19

Tip: for progressively filtering out what you don't want: grep -v "hede" | grep -v "hihi" | ...etc.

@Olaf Dietsche 2015-04-26 05:42:15

Or using only one process grep -v -e hede -e hihi -e ...

@Putnik 2016-12-09 15:29:17

Or just grep -v "hede\|hihi" :)

@codeforester 2018-03-11 18:35:45

If you have many patterns that you want to filter out, put them in a file and use grep -vf pattern_file file

@Amit Naidu 2018-06-03 10:54:02

Or simply egrep or grep -Ev "hede|hihi|etc" to avoid the awkward escaping.

Related Questions

Sponsored Content

7 Answered Questions

[SOLVED] Regular expression to stop at first match

  • 2010-03-23 20:36:35
  • publicRavi
  • 540496 View
  • 492 Score
  • 7 Answer
  • Tags:   regex

19 Answered Questions

[SOLVED] How do you use a variable in a regular expression?

  • 2009-01-30 00:11:05
  • JC Grubbs
  • 687943 View
  • 1258 Score
  • 19 Answer
  • Tags:   javascript regex

73 Answered Questions

11 Answered Questions

[SOLVED] Converting user input string to regular expression

  • 2009-05-17 14:20:18
  • Gordon Gustafson
  • 263040 View
  • 317 Score
  • 11 Answer
  • Tags:   javascript html regex

12 Answered Questions

[SOLVED] Regular Expressions: Is there an AND operator?

  • 2009-01-22 16:49:14
  • Hugoware
  • 711360 View
  • 661 Score
  • 12 Answer
  • Tags:   regex lookahead

34 Answered Questions

[SOLVED] RegEx match open tags except XHTML self-contained tags

  • 2009-11-13 22:38:26
  • Jeff
  • 2710690 View
  • 1324 Score
  • 34 Answer
  • Tags:   html regex xhtml

18 Answered Questions

[SOLVED] How do you access the matched groups in a JavaScript regular expression?

  • 2009-01-11 07:21:20
  • nickf
  • 723035 View
  • 1280 Score
  • 18 Answer
  • Tags:   javascript regex

8 Answered Questions

[SOLVED] Is there a regular expression to detect a valid regular expression?

  • 2008-10-05 17:07:35
  • psytek
  • 199557 View
  • 970 Score
  • 8 Answer
  • Tags:   regex

15 Answered Questions

[SOLVED] What is a non-capturing group in regular expressions?

5 Answered Questions

[SOLVED] \d is less efficient than [0-9]

Sponsored Content