获取重叠的正则表达式结果并使用替换javascript

时间:2017-05-03 19:16:40

标签: javascript jquery regex

我想要完成的任务:

我正在尝试创建一个可以执行以下操作的正则表达式程序:

A^C + B^C = (A + B)^C

我的正则表达方式:

/(^|[^^*/\dt.-])(-?)(\d+\.?(?:\d+)?)x(?:(?:\^(\d+\.?(?:\d+)?))|(?:\^\(([\s\S]+)\)))?([+-])(-?)(\d+\.?(?:\d+)?)x(?:(?:\^(\d+\.?(?:\d+)?))|(?:\^\(([\s\S]+)\)))?(?=$|[^(^*/!\d\.])/

分解成块:

/(^|[^^*/\dt.-])个字符不应该在匹配之前

(-?)(\d+\.?(?:\d+)?)x a(负数)后跟x

(?:(?:\^(\d+\.?(?:\d+)?))|(?:\^\(([\s\S]+)\)))?可能x被提升到括号中的数字或其他内容

([+-])正负

(-?)(\d+\.?(?:\d+)?)x a(负数)后跟x

(?:(?:\^(\d+\.?(?:\d+)?))|(?:\^\(([\s\S]+)\)))?同样的力量

不应该跟随匹配的

(?=$|[^(^*/!\d\.])/个字符

示例文字

它的作用是找到类似于第四个例子的匹配,其中括号之间的幂不相同。然后我检查我在替换正则表达式方法中提供的函数,即幂是相同的,并且可以简化等式。

5-3x+7x //Here it finds 3x+7x

3x^2+4x^2-5 //Here it finds 3x^2+4x^2

3x^2+5x^3+8x^3 //Here it finds 3x^2 + 5x^3, but not 5x^3 + 8x^3 < - 问题

3x^(5x+7x)+5x^(6x+6x) //Here it finds 3x^(5x+7x)+5x^(6x+6x) but not the inner 5x+7x and 6x+6x < - 也是问题

我尝试过的事情:

我尝试实施此解决方案,但我不知道如何在正则表达式替换功能中使用它:stackoverflow: How can I match overlapping strings with regex?

我的代码:

预期结果:3x^2+13x^3
实际结果:3x^2+5x^3+8x^3(与输入相同)

var solvedEquation = "3x^2+5x^3+8x^3";

addXterms();

console.log(solvedEquation);

function addXterms() {
  var legitPattern = true;
  var addVariablesPattern = /(^|[^^*/\dt.-])(-?)(\d+\.?(?:\d+)?)x(?:(?:\^(\d+\.?(?:\d+)?))|(?:\^\(([\s\S]+)\)))?([+-])(-?)(\d+\.?(?:\d+)?)x(?:(?:\^(\d+\.?(?:\d+)?))|(?:\^\(([\s\S]+)\)))?(?=$|[^(^*/!\d\.])/g;
  while (addVariablesPattern.test(solvedEquation)) {
    solvedEquation = solvedEquation.replace(addVariablesPattern, function (match, operator1, minusSign1, num1, numPower1, parPower1, operator2, minusSign2, num2, numPower2, parPower2) {
        var result;

        if (numPower1 == numPower2 && parPower1 == parPower2) {
            num1 = parseFloat(num1) * (minusSign1 == "-" ? -1 : 1);
            num2 = parseFloat(num2) * (minusSign2 == "-" ? -1 : 1);

            if (operator2 == "+") {
                result = num1 + num2;
            } else {
                result = num1 - num2;
            }
            equationSolved = false;

            if (numPower1 != "" && typeof numPower1 != "undefined") {
                return operator1 + result + "x^" + numPower1;
            } else if (parPower1 != "" && typeof parPower1 != "undefined") {
                return operator1 + result + "x^(" + parPower1 + ")";
            } else {
                return operator1 + result + "x";
            }

        } else {
            legitPattern = false;
            return match;
        }
    });
  }
}

0 个答案:

没有答案