Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx that matches a word that NOT succeeds another one

How could a JavaScript RegEx be written, so that it matches for example the word cube, but only if the word small is not present in the 20 character range before this word.

RegEx should match:

  • cube
  • red cube
  • wooden cube
  • small................cube

RegEx should not match:

  • small cube
  • small red cube
  • small wooden cube
  • ..........small......cube
  • any sphere

Currently my regex looks and works like this:

> var regex = /(?:(?!small).){20}cube/im;
undefined
> regex.test("small................cube")     // as expected
true
> regex.test("..........small......cube")     // as expected
false
> regex.test("01234567890123456789cube")      // as expected
true
> regex.test("0123456789012345678cube")       // should be `true`
false
> regex.test("cube")                          // should be `true`
false

There must be 20 characters in front of cube, where each is not the first character of small. But here is the problem: If cube appears within the first 20 characters of a string, the RegEx does not match of course, because there are not enough characters in front of cube.

How can the RegEx be fixed, to prevent these false negatives?

like image 928
hiddenbit Avatar asked Oct 31 '22 20:10

hiddenbit


1 Answers

You can use this regex:

.*?small.{0,15}cube|(.*?cube)

And use matched group #1 for your matches.

Online Regex Demo

like image 170
anubhava Avatar answered Nov 09 '22 14:11

anubhava