user3649739 user3649739 - 1 month ago 4x
Python Question

Prioritize OR Pipe in Regex based on first match in the regex not in the source?

If I do a regex with an

pipe like

It always finds the first match in order in my source e.g.

  • ABC=A

  • BCA=B

  • CBA=C

I am trying in fact to set it up so the order I put the options is the order it looks for. In other words in the example I have it would always look for 'A' first and if found stop searching and return
, if not it would search for
and if it didn't find that it would search for
and if found return
. Is there a way to prioritize it that way so in fact in the above example it would find
in each case?


Building on @WiktorStribi┼╝ew's example:


basically, the negative lookahead is used, and then cascaded for all the Or pipes (using the parentheses).

  1. Match A (A)

  2. Match B if not followed by A (B)(?!.*A)

  3. Match C if not followed by B or A (C)(?!.*B)(?!.*A)