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)
{
System.out.println(part);
}
//for degree
String[] degree = str.split("+\\+?\\d");
for (String part : degree)
{
System.out.println(part);
}
Already consulted this.
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
Code:
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With