有两个有意义的小组,我如何引用不匹配的小组?

时间:2017-04-04 23:27:15

标签: javascript regex

例如:

我想匹配此

##A##B##A##
##B##A##B##

但没有这个

##A##A##A##
##A##A##B##
##A##B##B##
##B##A##A##
##B##B##A##
##B##B##B##

不使用此:##A##B##A##|##B##A##B##

我的方法是##((A)|(B))##?##\1##,但不知道该放入?

的内容

我不太清楚如何提出这个问题,但如果你有更好的东西,我会编辑它。

1 个答案:

答案 0 :(得分:2)

您可以使用负面预测(?!...),如下所示:

/##(A|B)##(?!\1)[AB]##\1##/

<强>解释

##     : litteral "##"
(A|B)  : litteral "A" or "B" grouped as \1
##     : litteral "##"
(?!\1) : not \1 (doesn't consume from the input string so we need the following [AB])
[AB]   : litteral "A" or "B" (set)
##     : litteral "##"
\1     : the result of the group \1
##     : litteral "##"

示例:

var tests = ["##A##B##A##","##B##A##B##","##A##A##A##","##A##A##B##","##A##B##B##","##B##A##A##","##B##B##A##","##B##B##B##"];

var regex = /##(A|B)##(?!\1)[AB]##\1##/;
tests.forEach(function(test) {
  console.log(test, " => ", regex.test(test));
});