Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use regular expression for calculator input with javascript?

I am trying to write simple calculator with JavaScript. I want to check if user input is correct or not. I wrote regular expression in order to make sure user input is proper but it is not working. What I want to do is a simple rule which is operator(/*-+) should be followed by operand(0-9) but first operator can be - or +. The regular expression below is not working. What is my mistake?

^[-+]?[0-9]{0,}([-+*/]?)[0-9]+$
like image 322
hrn Avatar asked Feb 12 '23 17:02

hrn


2 Answers

Your expression looks for an optional - or + followed by zero or more digits ([0-9]{0,}). I think you probably wanted one or more (+). Similarly, the ? in ([-+*/]?) makes the operator optional. You probably also want to capture the various parts.

It is fine when I have something one operator between two operand but when I do 9+9+9 which is more then two it is not working.

If you want to allow additional operators and digits following them, you have to allow the latter part to repeat.

Here's my rough take:

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

Live Example (But there's something not quite right happening with the capture groups if you have three or more terms.)

Changes I made:

  1. Use \d rather than [0-9] (\d stands for "digit")

  2. Put the digits and the operators in capture groups.

  3. Don't make the digits or operator optional.

  4. Allow optional whitespace (\s*) in various places.

  5. The (?: _________ )+ is what lets the part within those parens repeat.

  6. Allow a - or + in front of the second group of digits, but only if preceded by a space after the operator.

like image 120
T.J. Crowder Avatar answered Feb 15 '23 09:02

T.J. Crowder


^[-+]?

Is correct, but then

[0-9]{0,}

Is not, you want + quantifier as if you use {0,} (which is the same as *) you could have "+*9" being correct. Then,

([-+*/]?)[0-9]+

Is wrong, you want :

([-+*/]+[-+]?[0-9]+)*

So you will have for instance *-523+4234/-34 (you can use an operand on an either negative or positive number, or not precised number which would mean obviously positive)

So finally, you would have something like :

^[-+]?[0-9]+([-+*/]+[-+]?[0-9]+)*$

Of course, you can replace class [0-9] with \d

like image 32
servabat Avatar answered Feb 15 '23 09:02

servabat