我试图从javascript中的字符串中提取多项式字符串的不同部分,如变量,系数和幂。到目前为止,我能够从一个简单的多项式字符串中提取它们,例如“-13x ^ 2 + 2-12x ^ 4”。
我想将其扩展为从相对复杂的多项式字符串中提取。类似于“-13x ^ 2y ^ 3 + 2-12x ^ -4”。
以下是我的代码:
function extractPolynomial(polynomialStr) {
var arr = [];
polynomialStr = polynomialStr.match(/[+-]?\d+(x|y)(\^\d)*|[+-\s]\d+/g);
polynomialStr.forEach(function (match) {
var vals = match.split('^');
var coeff = parseInt(vals[0]);
var variable = vals[0].match(/[a-z]/gi) ? vals[0].match(/[a-z]/gi)[0] : "";
var power = 1;
if(vals.length > 1){
power = parseInt(vals[1]);
}
else {
if (variable === "") {
power = 0;
}
else {
power = 1;
}
}
arr.push({
coeff: coeff,
variable: variable,
power: power
})
});
return arr;
}
答案 0 :(得分:0)
通过对正则表达式的一些研究,我得到了我想要的东西。 以下是从多项式中提取所有信息的函数:
function extractPolynomial(polynomialStr) {
var arr = [];
polynomialStr = polynomialStr.match(/[+-]?\d*(x|y)(\^\d)*((y|x)(\^\d)*)*|[+-\s]\d+/g);
polynomialStr.forEach(function (match) {
var variable = match.match(/([a-z]\^\d|[a-z])/gi) ? match.match(/([a-z]\^\d|[a-z])/gi).join("") : " ";
var coeff = parseFloat(match.split(variable)[0]);
var power = 1;
var variables = [];
if (variable != " ") {
var tempVars = variable.match(/([a-z]\^\d|[a-z])/gi);
for (var i = 0; i < tempVars.length; i++) {
var oneVariable = { variable: "", power: 0 };
oneVariable.variable = tempVars[i].match(/[a-z]/gi)[0];
var tempV = tempVars[i].split("^");
if (tempV.length > 1) {
oneVariable.power = parseFloat(tempV[1]);
}
else {
oneVariable.power = 1;
}
variables.push(oneVariable);
}
}
else {
variables.push({ variable: "", power: 0 });
}
arr.push({
coeff: coeff,
variables: variables
});
});
return arr;
};