Regex for polynomial expression in Java

Viewed 264

could someone help me create a Java regex for the following polynomial expression?

Expression: 9x^2 + 4x + 2


Ive so far not been able to map the constant and im not sure if this is the best way but this is whats from my best understanding:

(-?\b\d+) [xx] || ^ (-?\d+\b)


Any help is much appreciated thanks :)

1 Answers

Here is a general regex pattern, which should work for a polynomial of any order:

^\d{0,}(?:[a-z](?:\^\d+)?)?(?: [+-] \d{0,}(?:[a-z](?:\^\d+)?)?)*$

Demo

I will explain the first portion of the regex, which matches any single polynomial term. The second repeating portion of the regex just recycles this pattern, with a +/- separator in between.

\d{0,}          match zero or more numbers (coefficients)
(?:             turn off capturing
    [a-z]       match a single variable letter
    (?:\^\d+)?  then match an optional exponent term
)?              close group

Note that we handle the optional exponent by grouping it with the variable. Then, we make that entire group optional.

Related