我希望创建一个符合以下要求的Regex:
( 1)必须充当“和”陈述
( 2)这两个词都应该在一个范围内
( 3)它不计算同一个词中的两个。
到目前为止,我有这个工作REGEX,它满足1和2。
/(word1|word2)(?:\W+\w+){0,3}?\W+(word1|word2)/i示例Regex:
/(cat|dog)(?:\W+\w+){0,3}?\W+(cat|dog)/i
现在可以工作的字符串
我不想要的字符串
像“猫吓到了另一只猫”这样的短语。将与REGEX匹配,因为它正在搜索第二组中的任何单词,其中包括cat。不过,我不想让它自己去寻找。我只想找狗。
发布于 2013-12-20 13:21:23
不如:
/(cat|dog)(?:\W+\w+){0,3}?\W+(?!\1)(cat|dog)/解释:
The regular expression:
(?-imsx:(cat|dog)(?:\W+\w+){0,3}?\W+(?!\1)(cat|dog))
matches as follows:
NODE EXPLANATION
----------------------------------------------------------------------
(?-imsx: group, but do not capture (case-sensitive)
(with ^ and $ matching normally) (with . not
matching \n) (matching whitespace and #
normally):
----------------------------------------------------------------------
( group and capture to \1:
----------------------------------------------------------------------
cat 'cat'
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
dog 'dog'
----------------------------------------------------------------------
) end of \1
----------------------------------------------------------------------
(?: group, but do not capture (between 0 and 3
times (matching the least amount
possible)):
----------------------------------------------------------------------
\W+ non-word characters (all but a-z, A-Z,
0-9, _) (1 or more times (matching the
most amount possible))
----------------------------------------------------------------------
\w+ word characters (a-z, A-Z, 0-9, _) (1 or
more times (matching the most amount
possible))
----------------------------------------------------------------------
){0,3}? end of grouping
----------------------------------------------------------------------
\W+ non-word characters (all but a-z, A-Z, 0-
9, _) (1 or more times (matching the most
amount possible))
----------------------------------------------------------------------
(?! look ahead to see if there is not:
----------------------------------------------------------------------
\1 what was matched by capture \1
----------------------------------------------------------------------
) end of look-ahead
----------------------------------------------------------------------
( group and capture to \2:
----------------------------------------------------------------------
cat 'cat'
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
dog 'dog'
----------------------------------------------------------------------
) end of \2
----------------------------------------------------------------------
) end of grouping
----------------------------------------------------------------------https://stackoverflow.com/questions/20703980
复制相似问题