我想从一个简单的数学表达式字符串中提取数字;我首先用空格替换字符串中的所有数学字符,然后尝试用空格拆分字符串,然后将数字放入 ArrayList
public ArrayList<Integer> retriveNumbers(String Expr) {
ArrayList<Integer> numbers = new ArrayList();
Expr = Expr.replaceAll("^", " ");
Expr = Expr.replaceAll("[*]", " ");
Expr = Expr.replaceAll("/", " ");
Expr = Expr.replaceAll("[+]", " ");
Expr = Expr.replaceAll("-", " ");
Expr = Expr.replaceAll("%", " ");
String[] elements = Expr.split(" ");
for(String e : elements){
numbers.add(Integer.parseInt(e));
}
return numbers;
}
但是当我测试它时,我在输出中给出错误numbers.add(Integer.parseInt(e));
Calculator c1 = new Calculator();
ArrayList<Integer> arr = c1.retriveNumbers("4*5-2+1");
for(int i: arr)
System.out.println(i);