[英]How do I extract the coefficients and variables of an algebraic expression in an array using regex in javascript?
我想将代数部分存储在一个数组中。 目前,我有这个,但它没有完全工作。
function exp(term) {
var container = [];
if (term[0] === '-') {
container[0] = '-1';
container[1] = term.match(/([0-9]+)/g)[0];
container[2] = term.match(/([a-zA-Z]+)/g)[0];
}
else {
container[0] = '0';
container[1] = term.match(/([0-9]+)/g)[0];
container[2] = term.match(/([a-zA-Z]+)/g)[0];
}
return container;
}
console.log(exp('-24mn')); //should output ['-1', '24', 'mn']
console.log(exp('-100BC')); //should output ['-1', '100', 'BC']
console.log(exp('100BC')); //should output ['0', '100', 'BC']
console.log(exp('100')); //should output ['0', '100', '']
console.log(exp('BC')); //should output ['0', '0', 'BC']
console.log(exp('-bC')); //should output ['-1', '0', 'bC']
console.log(exp('-100')); //should output ['-1', '100', '']
但如果可能的话,我真正想要的是一个长度为 2 的数组,其中包含系数和变量,例如:
console.log(exp('-24mn')); //should output ['-24', 'mn']
console.log(exp('-100BC')); //should output ['-100', 'BC']
console.log(exp('100BC')); //should output ['100', 'BC']
console.log(exp('100')); //should output ['100', '']
console.log(exp('BC')); //should output ['0', 'BC']
console.log(exp('-bC')); //should output ['-1', 'bC']
console.log(exp('-100')); //should output ['-100', '']
我只使用长度为 3 的数组方法,因为我不知道如何处理只有负号后跟“-bC”等变量以及“BC”等变量的情况。 任何帮助将不胜感激。 提前致谢!
您可以使用组来捕获这两个部分并添加一些额外的逻辑来处理输入中不存在数字的情况:
function exp(term) {
const matches = term.match(/(-?[0-9]*)([a-zA-Z]*)/);
return [convertNumMatch(matches[1]), matches[2]];
}
function convertNumMatch(numMatch) {
if (!numMatch)
return '0';
else if (numMatch === '-')
return '-1';
else
return numMatch;
}
您尝试的模式包含所有可选部分,这些部分也可以匹配空字符串。
您可以交替使用 4 个捕获组。 然后返回一个包含第 1 组和第 2 组的数组,或包含第 3 组和第 4 组的数组。
0
和-1
的值可以通过检查组 3(在代码中表示为m[3]
)是否存在来确定。
^(-?\d+)([a-z]*)|(-)?([a-z]+)$
^
字符串开头(-?\d+)
捕获组 1匹配可选的-
和 1+ 位([az]*)
捕获组 2捕获可选字符 a-zA-Z|
或者(-)?
可选捕获组 3匹配-
([az]+)
捕获组 4匹配 1+ 字符 a-zA-Z$
字符串结尾使用/i
标志使用不区分大小写匹配的示例:
const regex = /^(-?\d+)([az]*)|(-)?([az]+)$/gi; const exp = str => Array.from( str.matchAll(regex), m => m[4]? [m[3]? -1: 0, m[4]]: [m[1], m[2]] ); [ "-24mn", "-100BC", "100BC", "100", "BC", "-bC", "-100", "" ].forEach(s => console.log(exp(s)) );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.