簡體   English   中英

如何使用 javascript 中的正則表達式提取數組中代數表達式的系數和變量?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM