[英]How to not split decimal point in math equation string using Regex in Javascript
I have this string that contain Math equation.我有这个包含数学方程的字符串。 And I want to split it based on the operator between number.我想根据数字之间的运算符对其进行拆分。 Because later I want to use it with eval()
to do math operation.因为后来我想用它和eval()
来做数学运算。
Like this:像这样:
var myString = "25+15-10/555"
var newString = myString.split(/([x+-/])/).filter(Boolean);
Which I have successfully split the string like I want:我已经成功地拆分了我想要的字符串:
output: ["25", "+", "15", "-", "10", "/", "555"]
The problem is If I have decimal point in my string.问题是如果我的字符串中有小数点。 It will separate a number that actually a decimal point number:它将分隔一个实际上是小数点的数字:
var myString = "2.5+15-55.50"
var newString = myString.split(/([x+-/])/).filter(Boolean);
output: ["2", ".", "5", "+", "15", "-", "55", ".", "50"]
As you can see, it separate 2.5
and 55.50
.如您所见,它将2.5
和55.50
分开。 How can I achieve this output: ["2.5", "+", "15", "-", "55.50"]
?我怎样才能实现这个 output: ["2.5", "+", "15", "-", "55.50"]
?
What should I do to my Regex?我应该如何处理我的正则表达式? Or maybe there's something wrong with it?或者它可能有什么问题?
You almost had the correct regex, problem with /([x+-/])/ is that the minus sign is interpreted as a range specifier in the character class, in this case indicating from plus (+) to slash (/).您几乎有正确的正则表达式,/([x+-/])/ 的问题是减号被解释为字符 class 中的范围说明符,在这种情况下表示从加号 (+) 到斜杠 (/)。 What you could do is either escape the minus sign with a backslash:您可以做的是用反斜杠转义减号:
/([x+\-/])/
Or move it to the end of the character class:或者将其移动到字符 class 的末尾:
/([x+/-])/
It's because -
in your characters list acts as range operator and has meaning all characters between from "+" till "/"
(similar to [az]
.这是因为-
在您的字符列表中充当范围运算符,并且具有all characters between from "+" till "/"
含义(类似于[az]
。
Move it to end of list or escape:将其移至列表末尾或转义:
var myString = "2.5+15-55.50" console.log(myString.split(/([x+\-/])/));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.