Regex for polynomial expression

一个人想着一个人 提交于 2021-01-29 17:45:55

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/36490757/regex-for-polynomial-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!