Search code examples
regexperlpcre

Regex match either or both, but not twice


I'm struggling to think how I'd go about writing a regex that would match any of these:

pirates
scallywags
pirates scallywags
scallywags pirates

But not any of these:

pirates pirates
scallywags scallywags
pirates booty scallywags
booty pirates

Of course I could list out all of the possible permutations as alternates:

(pirates|scallywags|pirates scallywags|scallywags pirates)

But I feel like there should be an easier/more efficient way.


Solution

  • Still not smart enough, but will work:

    ^(pirates|scallywags)(?! \1)( (pirates|scallywags))?$