What I'd do is String.replaceAll all non-digits with whitespace. Then String.split by whitespace.
package com.sandbox;
import java.util.Arrays;
public class Sandbox {
public static void main(String[] args) {
String input = "2x^4 - 45y^4";
input = input.replaceAll("\\D", " ");
String[] parts = input.split("\\W+");
System.out.println(Arrays.toString(parts));
}
}
This will print "[2, 4, 45, 4]"
Now that I understand @RohitJain's answer, it seems I'm including an unnecessary step. I guess I'll leave this here anyway since it does work, but I recommend his solution. His solution splits on all non digits. Since split excludes the delimiter, this also removes the non-digits.
\din java. Your code won't ocmpile.