1

I am developing a distributed calculator using JavaScript and PHP. The calculator should recognize parenthesis and should change the order of calculations according to parenthesis. All basic mathematical operations (*, /, +, -) have the same priority (unlike the common priority). I use the following regex to get user input and put in an array. This regex works well for positive numbers:

/\d*\.\d+|\d+|[()/*+-]/g

However, when it comes to negative numbers, it crashes because I use a recursive replacement function that replaces each pair of parenthesis (and the contents) with the result of the operations inside those parenthesis. I do this because this is a distributed calculator and I should perform each atomic operation at server side and then return the result back and show it in the history of the operations.

All I want is to detect negative numbers (to save them as only one element in the array). I think it should work in this way: when there are two consecutive operators (with zero or more whitespace characters between them), and the second operator is a minus sign (-), the minus sign should be concatenated to the following number (as the sign of the number). In addition, if the first number is preceded by a minus sign, the sign should be concatenated to that number.

4

1 回答 1

2

因为在 javascript 的正则表达式实现中没有后视,所以这并不像最初看起来那么简单。

这是一种方法。它假定首先删除了空格。

var m,
    tokens = [],
    rex = /(^|[(\/*+-])(-(?:\d*\.)?\d+)|[()\/*+-]|(?:\d*\.)?\d+/g,
    str = '-4-(-2*3)--4-2/-0.9-3+(3-4*-4)';

while ( m = rex.exec( str ) ) {
    if ( m[1] ) {
        tokens.push( m[1], m[2] );
    } else {
        tokens.push( m[0] );
    }
}

console.log( tokens );
// [ "-4", "-", "(", "-2", "*", "3", ")", "-", "-4", "-", "2", "/", "-0.9", "-", "3", "+", "(", "3", "-", "4", "*", "-4", ")" ]

在这里,使用捕获组来模拟后视()。如果在负数之前有字符串的开头^或运算符,则将运算符和负数分别添加到数组中。否则,将任何作为运算符添加到数组中。 m[1]m[2]-

或者,您可以使用

tokens = str.match( /(?:\d*\.)?\d+|[()\/*+-]/g );

然后遍历数组,如果你找到一个-跟随一个运算符,然后将它添加到下面的数字。

无论您采用哪种方式,一个简单的正则表达式都不会单独标记字符串,您需要使用条件语句来确定如何处理每个-.

于 2013-02-24T23:35:29.047 回答