Just get digits with the Regex:
String str = "3x^2";
String pattern = "(\\d+)";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(str);
ArrayList<Integer> numbers = new ArrayList<>();
Find with Matcher
all numbers and add them to the ArrayList
. Don't forget to convert them to int
, because m.group()
returns the String
.
while (m.find()) {
numbers.add(Integer.parseInt(m.group()));
}
And if your formula doesn't contain the second number, add there your desired default item.
if (numbers.size<2) {
numbers.add(1);
}
Finally print it out with:
for (int i: numbers) {
System.out.print(i + " ");
}
And the output for 3x^2
is 3 2
.
And for the 8x
it is 8 1
.