pythonregexregex-lookaroundsbackreference

Regex group with pipe (2 valid patterns), negative backreference to that group and choose the other one now


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.


Solution

  • It seems you could use:

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

    See an online demo