I am trying to capture from two different pattern sequences using a named capture group. This SO question solves the problem in PCRE using the mode modifier (?J)
, and this SO question solves a related problem in Python that I haven't succeeded at applying to my use case.
Example test strings:
abc-CAPTUREME-xyz-abcdef
abc-xyz-CAPTUREME-abcdef
Desired output:
CAPTUREME
CAPTUREME
CAPTUREME
appears on either the left or right of the xyz
sequence. My initial failed attempt at a regex looked like this:
r'abc-(xyz-(?P<cap>\w+)|(?P<cap>\w+)-xyz)-abcdef'
But in Python regexes that yields an error (?P<cap> A subpattern name must be unique)
and python doesn't support the (?J)
modifier that was used in the first answer above to solve the problem.
With a single capture group I can capture CAPTUREME-xyz
or xyz-CAPTUREME
, but I can't reproduce the example in the 2nd stack overflow article linked above using lookarounds. Every attempt to replicate the 2nd stack overflow article simply doesn't match my string and there are too many differences for me to piece together what's happening.
r'abc-(?P<cap>(xyz-)\w+|\w+(-xyz))-abcdef'