如何在javascript中使用正则表达式提取数组中代数表达式的系数和变量?
我想把代数部分存储在一个数组中。目前,我有这个,但它不完全工作如何在javascript中使用正则表达式提取数组中代数表达式的系数和变量?,javascript,regex,matching,Javascript,Regex,Matching,我想把代数部分存储在一个数组中。目前,我有这个,但它不完全工作 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]; } e
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]
)来确定
字符串的开头^
捕获组1匹配可选(?\d+)
和1+位-
捕获第2组捕获可选字符a-zA-z([a-z]*)
或|
可选捕获组3匹配(-)
-
捕获第4组匹配1+字符a-zA-z([a-z]+)
字符串结尾$
/i
标志使用不区分大小写匹配的示例:
const regex=/^(-?\d+)([a-z]*)|()([a-z]+)$/gi;
const exp=str=>Array.from(
str.matchAll(regex),m=>m[4]?[m[3]?-1:0,m[4]:[m[1],m[2]]
);
[
“-2400万”,
“-公元前100年”,
“公元前100年”,
"100",
“BC”,
“-bC”,
"-100",
""
].forEach(s=>
控制台日志(exp(s))
);代码>
^(-?\d+)([a-z]*)|(-)?([a-z]+)$