当组 1、2、3 或 4 之间没有实例时,如何匹配 (group2.*|^.*)group1?

How to match (group2.*|^.*)group1 when no instance of groups 1,2,3, or 4 are in between?

我正在使用 Python 3.4.

假设我们有四组由正则表达式组成

g1 = 'g11|g22|...|g1m'
g2 = 'g21|g22|...|g2n'
g3 = 'g32|g32|...|g3p'
g4 = 'g41|g42|...|g4q'

例如,g1 可能是 'chickens|horses|bonnet(?>!blue )'。这些组是不相交的:四个组中的任何一个元素都属于一个以上的组。这些组可以包含大于 1 的任意数量的元素。

我想匹配字符串 当且仅当 它包含 any group_1 的实例,这样:

  1. 组 1-4 中的任何一个实例都没有先于 said group_1 or
  2. 实例
  3. 组 1-4 中紧接 之前的任何组的实例说 group_1 的实例不是 group_2。

我要匹配的一些字符串:

  1. 'g11'
  2. 'g31 g11'
  3. 'g41g11'
  4. 'g11 g21 g11'(g11的第二个实例违反了规则2。g11的第一个实例没有,而且满足了规则1。)
  5. 'anything or nothing g11 anything or nothing'
  6. 'anything or nothing g31 anything or nothing g11'

一些我不想匹配的字符串:

  1. 'g31 g21 g11'
  2. 'g21 g11 g31'
  3. 'anything or nothing g21 anything or nothing g11 anything or nothing'

到目前为止尝试了什么:

^(?!(?:(?!g1|g2).)*(?:g21|g22)(?:(?!g31|g32|g41|g42).)*(?:g11|g12)).*?(?:g11|g12).*$

您可以尝试 this.See 演示。

https://regex101.com/r/hI0qP0/16