Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading