问题描述
如何编写JavaScript RegEx,以便它匹配例如单词 cube
,但仅限于单词 small
在此单词之前的20个字符范围内不存在。
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应匹配:
-
cube
-
red cube
-
木制立方体
-
small .......... ......立方体
cube
red cube
wooden cube
small................cube
RegEx不匹配:
-
小立方体
-
小红色立方体
-
小木制立方体
-
..........小......立方体
-
任何球体
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
那里必须在 cube
前面的20个字符,其中每个字符不是 small
的第一个字符。
但问题是:如果 cube
出现在字符串的前20个字符内,那么RegEx当然不匹配,因为没有足够的字符前面的立方体
。
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
.
如何修复RegEx,以防止这些误报?
How can the RegEx be fixed, to prevent these false negatives?
推荐答案
你可以使用这个正则表达式:
You can use this regex:
.*?small.{0,15}cube|(.*?cube)
并使用匹配第1组为您的比赛。
And use matched group #1 for your matches.
这篇关于RegEx匹配不成功的另一个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!