简体   繁体   English

如何使用 javascript 中的正则表达式提取数组中代数表达式的系数和变量?

[英]How do I extract the coefficients and variables of an algebraic expression in an array using regex in javascript?

I want to store the algebraic parts in an array.我想将代数部分存储在一个数组中。 Currently, I have this but it's not fully working.目前,我有这个,但它没有完全工作。

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', '']

But if possible, what I really want is an array of length 2 only, containing the coefficient and the variables like:但如果可能的话,我真正想要的是一个长度为 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', '']

I only did the array of length 3 approach because I don't know how to deal with a case where there's only a negative sign followed by variables like '-bC' and also only variables like 'BC'.我只使用长度为 3 的数组方法,因为我不知道如何处理只有负号后跟“-bC”等变量以及“BC”等变量的情况。 Any help will be greatly appreciated.任何帮助将不胜感激。 Thanks in advance!提前致谢!

Your can use groups to capture the two parts and add some additional logic for handling cases where the number is not present in the input:您可以使用来捕获这两个部分并添加一些额外的逻辑来处理输入中不存在数字的情况:

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;
}

The pattern that you tried, contains all optional parts which could also match an empty string.您尝试的模式包含所有可选部分,这些部分也可以匹配空字符串。

You could use an alternation with 4 capture groups.您可以交替使用 4 个捕获组。 Then return an array with either group 1 and 2, or an array with group 3 and 4.然后返回一个包含第 1 组和第 2 组的数组,或包含第 3 组和第 4 组的数组。

The value of 0 and -1 can be determined by checking if group 3 (denoted as m[3] in the code) exists. 0-1的值可以通过检查组 3(在代码中表示为m[3] )是否存在来确定。

^(-?\d+)([a-z]*)|(-)?([a-z]+)$
  • ^ Start of string ^字符串开头
  • (-?\d+) Capture group 1 Match optional - and 1+ digits (-?\d+)捕获组 1匹配可选的-和 1+ 位
  • ([az]*) Capture group 2 Capture optional chars a-zA-Z ([az]*)捕获组 2捕获可选字符 a-zA-Z
  • | Or或者
  • (-)? Optional capture group 3 Match -可选捕获组 3匹配-
  • ([az]+) Capture group 4 Match 1+ chars a-zA-Z ([az]+)捕获组 4匹配 1+ 字符 a-zA-Z
  • $ End of string $字符串结尾

Regex demo正则表达式演示

Example using a case insensitive match using the /i flag:使用/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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM