user3649739 user3649739 - 3 months ago 8
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

OR
pipe like
(A|B|C)


https://regex101.com/r/gB1eP0/4

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
A
, if not it would search for
B
and if it didn't find that it would search for
C
and if found return
C
. Is there a way to prioritize it that way so in fact in the above example it would find
A
in each case?

Answer

Building on @WiktorStribiżew's example:

(A|(B|C(?!.*B))(?!.*A))

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)

https://regex101.com/r/zQ3pW0/1

Comments