Home > OS >  How can I check if an arithmetic expression is correct with a regex?
How can I check if an arithmetic expression is correct with a regex?

Time:04-27

I am currently learning regular expressions.

In order to learn the regular expressions, tried to verify a simple arithmetic expression with the regular expression, for which I defined several conditions and prepared a test cases.

The conditions are as follows:

  1. All operands can be one or more consecutive digits, and the operator must be a single digit operator corresponding to , -, *, /.

  2. Expressions may consist of only one or more operands without operators.

  3. If not condition 2, the expressions must start with an operand and end with an operand.

  4. There may or may not be a space between the operand and the operator.

tase cases:

2 3*4/2
2   3
2   3   2
2 3 2
2 3*4/2 
2   3/

2   3   2-
2 3 2*
2   3 * 4 / 2
2   3 *4 /2
2
22 32*34/21
22   3    2 * 34 /21
22 32*34/
35125125

I wrote the following regular expression.

^\d (?:\s?[ \-*/]\s?\d )*$

And I was expecting something like this:

2 3*4/2              [pass]
2   3                [pass]
2   3   2            [pass]
2 3 2                [pass]
2 3*4/2       
2   3/ 
      
2   3   2-
2 3 2*    
2   3 * 4 / 2        [pass]
2   3 *4 /2          [pass]
2                    [pass]
22 32*34/21          [pass]
22   3    2 * 34 /21    
22 32*34/
35125125             [pass]

But I got the following result:

enter image description here

The case where the expression ends with an operator is also included.

Could you please let me know what am I missing?

CodePudding user response:

You may try this:

^\d ( *[ =*/-] *\d )*$

You were using \s in your regex which is causing the issue as it covers newline characters. I replaced that by space.

Demo

  • Related