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:
-
All
operandscan be one or more consecutivedigits, and theoperatormust be a single digit operator corresponding to+,-,*,/. -
Expressions may consist of only one or more operands without operators.
-
If not condition 2, the expressions must start with an operand and end with an operand.
-
There may or may not be a
spacebetween 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:
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.
