简体   繁体   中英

How can I divide the following equation by regex?

This is my equation

5x^2 + 3x - 5 = 50

I have used this regex

/([+|-])([1-9][a-z])+|([1-9][a-z])+|([+|-])([1-9])+|([1-9])+/mg

but it does not give the results I want.

I want to divide my equation like this

array(
 5x^2 ,
 3x ,
 -5 ,
 =50
)

As a starting point, you could split your string by several mathematical operator symbols (for instance + , - , * , / and = ). Then you get an array of terms but without the operators that were used to split the string:

 const string = "5x^2 + 3x - 5 = 50"; const regex = /\\+|\\-|\\*|\\/|=/g; const result = string.split(regex); console.info(result);

To retrieve the delimiter characters as well, have a look at this StackOverflow post for example.

First remove the whitespaces.
Then match optional = or - followed by what's not = or - or +

Example snippet:

 var str = "5x^2 + 3x - 5 = 50"; let arr = str .replace(/\\s+/g, '') .match(/[=\\-]*[^+=\\-]+/g); console.log(arr);

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