gpt4 book ai didi

python - 命名组内的非捕获组

转载 作者:行者123 更新时间:2023-12-01 08:00:45 25 4
gpt4 key购买 nike

我想将一组字符串与前缀或后缀匹配,例如

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)

关于python - 命名组内的非捕获组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55745959/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com