如何使用javascript的计算器输入使用正则表达式? [英] How to use regular expression for calculator input with javascript?

查看:131
本文介绍了如何使用javascript的计算器输入使用正则表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用JavaScript编写简单的计算器。我想检查用户输入是否正确。我写了正则表达式,以确保用户输入正确,但它不起作用。我想要做的是一个简单的规则,运算符(/ * - +)后面应该是操作数(0-9),但第一个运算符可以是 - 或+。下面的正则表达式不起作用。我错了什么?

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


解决方案

你的表达式查找可选的 - + ,然后是或更多位数( [0-9] {0,} )。我想你可能想要一个或多个( + )。同样,([ - + * /]?)中的使运算符可选。您可能还想捕获各个部分。


当我在两个操作数之间有一个运算符但是当我做9+时,这很好9 + 9多于两个它不起作用。


如果你想允许跟随它们的其他运算符和数字,你有允许后一部分重复。



这是我粗略的看法:

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

实例 (但如果您有三个或更多术语,捕获组会发生一些不太正确的事情。)



我所做的更改:


  1. 使用 \d 而不是 [0-9] \d 代表数字)


  2. 将数字和运算符放在捕获组中。


  3. 不要使数字或运算符可选。


  4. 允许可选空格(


  5. (?:_________)+ 是让那些parens中的部分重复的原因。


  6. 允许 - 或在第二组数字前面的 + ,但前提是在运算符后面有一个空格。



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]+$

解决方案

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.

这篇关于如何使用javascript的计算器输入使用正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆