javascript - 如何在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”等变量的情况。任何帮助将不胜感激。提前致谢!
解决方案
您尝试的模式包含所有可选部分,这些部分也可以匹配空字符串。
您可以交替使用 4 个捕获组。然后返回一个包含第 1 组和第 2 组的数组,或包含第 3 组和第 4 组的数组。
0
和的值-1
可以通过检查组 3(m[3]
在代码中表示)是否存在来确定。
^(-?\d+)([a-z]*)|(-)?([a-z]+)$
^
字符串的开始(-?\d+)
捕获组 1匹配可选-
和 1+ 位([a-z]*)
捕获组 2捕获可选字符 a-zA-Z|
或者(-)?
可选捕获组 3匹配-
([a-z]+)
捕获组 4匹配 1+ 字符 a-zA-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]]
);
[
"-24mn",
"-100BC",
"100BC",
"100",
"BC",
"-bC",
"-100",
""
].forEach(s =>
console.log(exp(s))
);
推荐阅读
- sql - 我需要解决我正在尝试解决的这个 SQL 查询
- python - shutil.copytree 不断复制同一个文件夹
- react-native - 如何在 React Native 的下拉组件中实现单选按钮
- amazon-web-services - 使用 AWS SSM 参数存储的 SSL 证书
- sql - 在 SSRS 中为 table_name 使用参数
- kotlin - 如何从方法返回值中获取数据
- entity-framework-core - 如何停止 EF Core DbContext.SaveChanges 自动提交事务?
- marklogic - ML Gradle 部署带有注释问题的搜索选项
- node.js - Node JS - nodemailer & imap-simple - 识别线程
- python - 在 Python 中极快地生成 gamma 变量