Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Java regex, separate degree & coeff of polynomial




I'm having trouble understanding how regex syntax works. I try to use it to read from a String the coefficients and degrees of a polynomial. I saw similar questions, but it wasn't clear enough for me. Found how to extract coefficients but when I tried to do the same for the degree I found out it beats me. For an input like: 2x^3+3x^2

        //for coeff
        String[] coef = str.split("x\\^\\d+\\+?");
        for (String part : coef)

        //for degree
        String[] degree = str.split("+\\+?\\d");
        for (String part : degree)

Already consulted this.

like image 228
Lorena Sfăt Avatar asked Mar 16 '23 20:03

Lorena Sfăt

1 Answers

Rather than using 2 different regex and doing 2 split operations I suggest using a match with a single regex:

Pattern p = Pattern.compile( "(-?\\b\\d+)[xX]\\^(-?\\d+\\b)" );

You can then use Matcher.find() to get both coef (matched group 1) and degree (matched group 2).

RegEx Demo


String input = "2x^3-3x^-2";
Pattern p = Pattern.compile( "(-?\\b\\d+)[xX]\\^(-?\\d+\\b)" );
Matcher m = p.matcher( input );
while (m.find()) {
    System.out.println("Coef: " + m.group(1));
    System.out.println("Degree: " + m.group(2));
like image 127
anubhava Avatar answered Mar 29 '23 05:03