The regular expression /XY?|YX?/ Should work in accordance with each of the four situations you have listed. However, this is limited, since the regular expression that you use has a common match, you may get unexpected results.
Limited information is limited.
If this is a problem, perhaps add more requirements to the question.
Explanation:
The first half will try to match the regex X , and then try to match the times Y regex 0 or 1 . If regex X fails, then it will try the second half; which will try to match the regex Y , then try to match the time X regex 0 or 1 .
source share