[英]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.要检索定界符,请查看此 StackOverflow 帖子示例。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.