Java中用于多项式表达式的正则表达式

问题描述 投票:2回答:1

有人可以帮助我为以下多项式表达式创建Java正则表达式吗?

表达式:9x ^ 2 + 4x + 2


到目前为止,我还不能映射常数,我不确定这是否是最好的方法,但这是我的最佳理解:

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


非常感谢任何帮助:)

java regex regex-group regular-language polynomials
1个回答
4
投票

这里是一个常规的正则表达式模式,它适用于任何阶数的多项式:

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

Demo

我将解释正则表达式的第一部分,该部分与任何单个多项式项匹配。 regex的第二个重复部分只是循环使用此模式,在它们之间使用+/-分隔符。

\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

请注意,我们通过将可选指数与变量分组来处理它。然后,我们将整个组设为可选。

© www.soinside.com 2019 - 2024. All rights reserved.