How to use regular expression for calculator input with javascript?

后端 未结 2 1607
醉梦人生
醉梦人生 2021-01-19 08:02

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 prope

2条回答
  •  感动是毒
    2021-01-19 08:34

    ^[-+]?
    

    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

提交回复
热议问题