Reputation: 1223
I want to match one of a collection of strings with a prefix or suffix e.g.
the color is red
red is the color
I want to match groups color: red
So my first attempt was the obvious
(?<color>(?:the color is )(red|green|blue)|(red|green|blue)(?: is the color))
I was expecting this to match one group color: red
but it matches color: the color is red, 2: red
I have also tried with the (?>)
atomic operator
I tried moving the prefix / suffix groups outside of the named group:
(?:the color is )(?<color>red|green|blue)(?: is the color)
But this will only match strings with the prefix and suffix e.g. the color is red is the color
. Maybe I could use the lookahead or lookbehind operators with this?
I cannot use the (?J)
modifier as the regex engine I am using (python re
module does not support this.
Upvotes: 1
Views: 101
Reputation: 148870
I could not manage to use non capturing groups inside named groups, but at least this correctly extracts red
as group('color')
:
m = re.search(r"(?P<color>((red|green|blue)(?= is the color)|(?<=the color is )(red|green|blue)))", t)
Upvotes: 1