命名组中的非捕获组

Non capturing groups within named groups

我想用前缀或后缀匹配一组字符串中的一个,例如

the color is red red is the color

我要匹配组color: red

所以我的第一次尝试是显而易见的

(?<color>(?:the color is )(red|green|blue)|(red|green|blue)(?: is the color))

我原以为这会匹配一组 color: red 但它匹配 color: the color is red, 2: red

我也试过 (?>) 原子运算符

我尝试将前缀/后缀组移到命名组之外:

(?:the color is )(?<color>red|green|blue)(?: is the color)

但这只会匹配前缀为 后缀的字符串,例如the color is red is the color。也许我可以使用前瞻或后视运算符?

我不能使用 (?J) 修饰符作为我正在使用的正则表达式引擎(python re 模块不支持这个。

我无法设法在命名组内使用非捕获组,但至少这正确地将 red 提取为 group('color'):

m = re.search(r"(?P<color>((red|green|blue)(?= is the color)|(?<=the color is )(red|green|blue)))", t)