Home > Back-end >  Regex group with pipe (2 valid patterns), negative backreference to that group and choose the other
Regex group with pipe (2 valid patterns), negative backreference to that group and choose the other

Time:04-01

I came across this issue a few times now and I just can't find a solution for it.

Based on this post I try to achieve the opposite of him. Instead of only matching AA...AA and BB...BB I want to have a match only if the 2nd group is the opposite, maybe you could say like an if/else condition.

If AA search for BB elif BB search AA else no match.

AA...AA #no match
AA...BB #match
AA...CC #no match
BB...AA #match

In my case in the past I knew there will be exactly two patterns (AA or BB) but didn't know the order of it. So I need something like "Match pattern AA or BB, followed by anything I don't care, followed by the exact opposite of what matched earlier and nothing else".

I read several posts here at SO and the documentation of python, backreference is clear to me. I also came closer with the negative lookahead assertion but the problem here is that it just defines that it has to be different than the match previously, so if my captured group is (AA|BB) and it matched with AA, then (?!\1) will match anything else than AA.

I hope I made clear where I'm stuck and I'd appreciate any help.

CodePudding user response:

It seems you could use:

^(AA|BB).*(?!\1)(AA|BB)$

See an online demo


  • ^ - Start-line anchor;
  • (AA|BB) - A 1st capture group to match either 'AA' or 'BB';
  • .* - Match any 0 (Greedy) characters other than newline;
  • (?!\1) - A negative lookahead to assert position is not followed by the captured text from the 1st capture group (a backreference);
  • (AA|BB) - A 2nd capture group to match either 'AA' or 'BB';
  • $ - End-line anchor.
  • Related