Consider the following regular expression, where X and Y are any regex.
XY|YX|X|Y
This regex tests for X and/or Y, but has to double-check expressions if the "and" clause is not found.
What is the best way to match X and/or Y?
The regex /XY?|YX?/ should work to match each of the four situations you listed. This is limited however, as if the regex you use have a common match, you may get unexpected results.
With limited information, comes limited solutions
If this is an issue, perhaps add more requirements to the question.
Explanation:
The first half will attempt to match the X regex then will attempt to match the Y regex 0 or 1 times. If the X regex fails, then it will try the second half; which will attempt to match the Y regex then will attempt to match the X regex 0 or 1 times.
[XY]+ to get any number of Xs and Ys (so includes XYYXYX, etc).
Or...
[XY]{1,2} to select 1-2 Xs and Ys (which only includes your 4 examples).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With