Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex X and/or Y

Tags:

java

regex

php

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?

like image 379
FThompson Avatar asked Oct 22 '22 07:10

FThompson


2 Answers

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.

like image 168
Craig Avatar answered Oct 24 '22 04:10

Craig


[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).

like image 41
Sam Avatar answered Oct 24 '22 05:10

Sam