简体   繁体   中英

negative number in parentheses using javascript

I use match to split a mathematics expression into separated strings and save them in an array.

var STRING = ST.match(/\d*\.\d+|\d+|[()/*+-]/g);

but this method separate everything including negative numbers which are inside parentheses. For example (-2+4) does not give me -2, instead it saves - in one index of STRING array and 2 in the next index. Is there anyway use match and save negative numbers which are in the parentheses?

This is what I want: (-2+4):

STRING[0] give me (
STRING[1] give me -2
STRING[2] give me +
STRING[3] give me 4
STRING[4] give me )

and if there is no negative number work as normal: (2+4):

STRING[0] give me (
STRING[1] give me 2
STRING[2] give me +
STRING[3] give me 4
STRING[4] give me ) 

I don't think it's possible to parse complex cases like "(-2+4*-(3.5--8))" with just a regex especially given we don't have negative look behind in javascript.

A solution would be to postprocess your match array by merging signs when they're between a separator and an unsigned expression.

In my opinion a regex is useful here, but only for the primary tokenization. Most of the work will be ahead of you as you'll build the binary expression tree (or any other formal representation you choose).

Unfortunately, if what you're trying to do is parsing a mathematical expression, regexps can not be used.

RegExps can be used in languages that are describable by Regular Grammars and arithmetical expressions can not, they are described by a Context Free Grammar ( CFG ). If you want to parse, and perhaps interpret the result, you'll certainly need some stacked state machine.

You can look at something like this well known algorithm .

Hope this helps.

You can add an optional sign to the numbers, that would work with your example:

var STRING = ST.match(/-?\d*\.\d+|-?\d+|[()/*+-]/g);

However, that will also turn a minus operator into a sign. The expression (4-2) would give you { "(", "4", "-2", ")" } .

Also, it will happily "parse" an expression like +---((((*** without complaining. If you want a result that makes sense, you should parse it for real, not just split it with a regular expression.

我认为你在RegExp中有一些错误尝试这个,它对我有用:

var STRING = ST.match(/(\d*)(\.)(\d+)|(\d+)|[()\/*+-]/g);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM