首页 > 解决方案 > 如何在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”等变量的情况。任何帮助将不胜感激。提前致谢!

标签: javascriptregexmatching

解决方案


您尝试的模式包含所有可选部分,这些部分也可以匹配空字符串。

您可以交替使用 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))
);


推荐阅读