Regex for logical criteria

I have an input text box for entering logical criteria.
The following are the possible inputs:

1 OR 2 1 AND 2 (1 OR 2) AND 3 (1 OR 2) OR 3 (1 AND 2) AND 3 (1 AND 2) OR 3 1 AND (2 OR 3) 1 OR (2 OR 3) 1 AND (2 AND 3) 1 OR (2 AND 3) (1 OR 2) AND (3 OR 4) (1 OR 2) OR (3 OR 4) (1 AND 2) OR (3 AND 4) (1 OR 2) AND (3 OR 4) AND (5 OR 6) 

Can someone provide RegEx to confirm this input?

+4
source share
3 answers

Align only 1 and 2 or 4, without parentheses:

 ^\d+(?:\s*(?:AND|OR)\s*\d+)*$ 

Next, instead of each \d+ also allow the same expression, enclosed in parentheses:

 ^(?:\d+|\(\d+(?:\s*(?:AND|OR)\s*\d+)*\))(?:\s*(?:AND|OR)\s*(?:\d+|\(\d+(?:\s*(?:AND|OR)\s*\d+)*\)))*$ 

OK - this is not beautiful, but it works. Obviously, this involves only one level of parentheses.
As stated in the comments, depending on your language and requirements, you may find a more pleasant solution.

Working example: http://www.debuggex.com/r/eMBWubl5yAp6hUqQ

+1
source

Assuming you can insert parentheses, you cannot do this with direct regular expressions, because you cannot check arbitrary nested parentheses with a regular expression.

A more typical way of checking this input is to split the process into two steps. Use the regex family to tokenize input, and then use a simple grammar to validate the resulting token sequence. LALR (1) grammar, such as yacc support, makes this problem trivial.

I think there are several extended forms of regular expressions that add the necessary functionality that could correspond to arbitrarily nested parentheses. I must admit that I am not very familiar with any of them, since they quickly become more complicated to use than just writing some loop logic around a much simpler set of matches.

+2
source

You need to parse it using a loop with my solution. loop this regular expression (\({0,1}\d+ (OR|AND) \d+\){0,1}) and repeat the entire match value into a digit (for example, 1). until the text (\({0,1}\d+ (OR|AND) \d+\){0,1}) appears in the text. if you have only a digit, then this text is valid if it is invalid.

0
source

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


All Articles