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?
You can use this regex:
.*?small.{0,15}cube|(.*?cube)
And use matched group #1 for your matches.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With