Parse an arithmetic expression of 2 numbers and operation - one of «+», «-«, «*», «/» and «^» (power).
The result should be an array of: the first argument, the operation, the second argument.
For example,
"12 + 1" /* your code => */ '12', '+', '1' "5.1*2" /* your code => */ '5.1', '*', '2'
The expression may contain optional spaces.
The regexp is a number, followed by an operation and one more number.
A number including the optional decimal part is \d+(\.\d+)?.
Exclude groups you don’t need.
An operation is [-+*/^]. Here, hyphen - and caret '^' are not escaped, because they are not special on these positions inside [...]. When we put it into a literal JavaScript regexp, slash '/' needs to be escaped.
The full regexp is \d+(\.\d+)?\s[-+/^]\s*\d+(\.\d+)?. Optional whitespaces are added between the operation and numbers.
To capture each number and the operation, let’s add brackets around them:
(\d+(\.\d+)?)\s([-+/^])\s*(\d+(\.\d+)?).
Let’s see it in action:
var re = /(\d+(\.\d+)?)\s*([-+*\/^])\s*(\d+(\.\d+)?)/ var result = "12 + 1".match(re) alert(result)
The resulting array has full match on index 0, and then:
result[0] == "12+1"result[1] == "12"result[2] == undefinedresult[3] == "+"result[4] == "1"result[5] == undefined
Everything is fine, but we have extra undefineds. That’s because optional decimal part (\.\d+)? is absent here, but still occupies an array item.
In fact, even if it exists, we don’t want to capture it. The whole number is enough. So, we prepend the decimal part regexp by ?:
(?:\.\d+)?
var re = /(\d+(*!*?:*/!*\.\d+)?)\s*([-+*\/^])\s*(\d+(*!*?:*/!*\.\d+)?)/ var result = "12 + 1".match(re) result.shift() alert(result)