Regex that matches everything except given full word

Viewed 333

This is similar to javascript regular expression to not match a word, but the accepted answer shows a regex that doesn't match if the word is inside the line. I want to match everything except the full word. It will match "__lambda__".

This is also similar to my question Regex that match everything except the list of strings but that one gives a solution with String::split and I want to use normal match full string.

For example, it should match everything except /^lambda$/ I would prefer to have a regex for this, since it will fit my pattern patching function. It should match lambda_ or _lambda and everything else - except full "lambda" token.

I've tried this:

/^(.(?!lambda))+$/

and

/^((?!lambda).)+$/

this works

/^(.*(?<!lambda))$/

but I would prefer to not have to use a negative lookbehind if I can avoid it (because of browser support). Also, I have interpreter written in JavaScript that I need this for and I would like to use this in guest language (I will not be able to compile the regex with babel).

Is something like this possible with regex without lookbehind?

EDIT:

THIS IS NOT DUPLICATE: I don't want to test if something contains or doesn't contain the word, but if something is not exact word. There are not question on Stack Overflow like that.

Question Regex: Match word not containing has almost as correct an answer as mine, but it's not the full answer to the question. (It would help in finding solution, though.)

1 Answers

I was able to find the solution based on How to negate specific word in regex?

var re = /^(?!.*\blambda\b).*$/;

var words = ['lambda', '_lambda', 'lambda_', '_lambda_', 'anything'];
words.forEach(word => {
  console.log({word, match: word.match(re)});
});

Related