Regular expression of X and / or Y

Consider the following regular expression, where X and Y are any regular expression.

 XY|YX|X|Y 

This regular expression checks X and / or Y , but it needs to double-check the expression if the sentence "and" is not found.

What is the best way to match X and / or Y ?

+4
source share
3 answers

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 .

+2
source

[XY]+ to get any number of Xs and Ys (this includes XYYXYX , etc.).

Or...

[XY]{1,2} to select 1-2 Xs and Ys (which includes only your 4 examples).

0
source

For your X and/or Y requirement, what about this regular expression:

 (?:(?=.*?X)|(?=.*?Y))(X|Y) 

Live Demo: http://www.rubular.com/r/K36HjXzHLF

0
source

Source: https://habr.com/ru/post/1486972/


All Articles