What I'm trying to accomplish:
I'm trying to create a regex program that can do the following:
A^C + B^C = (A + B)^C
My regex:
/(^|[^^*/\dt.-])(-?)(\d+\.?(?:\d+)?)x(?:(?:\^(\d+\.?(?:\d+)?))|(?:\^\(([\s\S]+)\)))?([+-])(-?)(\d+\.?(?:\d+)?)x(?:(?:\^(\d+\.?(?:\d+)?))|(?:\^\(([\s\S]+)\)))?(?=$|[^(^*/!\d\.])/
Broken down into chunks:
/(^|[^^*/\dt.-])
characters that shouldn't precede the match
(-?)(\d+\.?(?:\d+)?)x
a (negative) number followed by an x
(?:(?:\^(\d+\.?(?:\d+)?))|(?:\^\(([\s\S]+)\)))?
possibly x raised to a number or something between parentheses
([+-])
plus or minus
(-?)(\d+\.?(?:\d+)?)x
a (negative) number followed by an x
(?:(?:\^(\d+\.?(?:\d+)?))|(?:\^\(([\s\S]+)\)))?
Same power thing
(?=$|[^(^*/!\d\.])/
characters that shouldn't follow the match
Sample text:
What it does is it finds matches like the fourth example here, where the powers, between the parentheses aren't the same. I then check in the function I provide in the replace regex method that the powers are the same, and the equation can be simplified.
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
<-- The problem
3x^(5x+7x)+5x^(6x+6x) //Here it finds 3x^(5x+7x)+5x^(6x+6x) but not the inner 5x+7x and 6x+6x
<--Also the problem
What I've tried:
I tried implementing this solution, but I don't know how to use that with the regex replace function: stackoverflow: How can I match overlapping strings with regex?
My code:
Expected result: 3x^2+13x^3
Actual result: 3x^2+5x^3+8x^3
(same as input)
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;
}
});
}
}