Skip to content
Advertisement

Regex for polynomial expression

I have a string that I hope is a polynomial expression, something like "2x^2-3x+1. I want to use a regex to group each term in the expression. I currently have "^(-?d?x(^d)?)+". I’m trying to capture a term as an optional minus sign, then a number, then x, then an optional exponent, which should be of the form “^someNumber”. So for my above polynomial, I’d want group 1 to be "2x^2", group 2 to be "-3x" and group 3 to be "+1". Firstly, if I have (someGroupExpression)+, will this generate a group for each someGroupExpression that occurs? Secondly, for the exponent part, I don’t want to have it be a nested group, as this would make it troublesome to loop through the term groups. How can I specify that the rules the exponent part should follow without making it a group? Please let me know if I can clarify the question.

Advertisement

Answer

To capture each sub expression in a group which is not nested or overlapping use the following regex.

Regex: ([+-]?[^-+]+)

Explanation: It will capture each sub expression of whole without overlapping each match.

Java Code

String exp = "2x^3+4x^2+5x-42";
Pattern pattern = Pattern.compile("([+-]?[^-+]+)");
Matcher matcher = pattern.matcher(exp);
int x=0;
while (matcher.find()) {
    x=x+1;
    System.out.println("Group "+x+": " + matcher.group(1));
}

Regex101 demo

Ideone Demo


A more robust regex which considers all sub-expressions would be:

Regex: ([+-]?(?:(?:d+x^d+)|(?:d+x)|(?:d+)|(?:x)))

Use \ in Java for double escaping. d will become \d, ^ becomes \^.

Regex101 Demo

Ideone Demo

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement