RegEx匹配不成功的另一个单词

hid*_*bit 5 javascript regex

如何编写JavaScript RegEx,以便它匹配例如单词cube,但只有在该单词small之前的20个字符范围内不存在该单词时.

RegEx应匹配:

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

RegEx不匹配:

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

目前我的正则表达式看起来像这样:

> 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
Run Code Online (Sandbox Code Playgroud)

前面必须有20个字符cube,每个字符不是第一个字符small.但问题是:如果cube出现在字符串的前20个字符内,则RegEx当然不匹配,因为前面没有足够的字符cube.

如何修复RegEx,以防止这些误报?

anu*_*ava 2

您可以使用这个正则表达式:

.*?small.{0,15}cube|(.*?cube)
Run Code Online (Sandbox Code Playgroud)

并使用匹配组 #1 进行匹配。

在线正则表达式演示