从String中提取数字和运算符

AR8*_*R89 2 java string expression numbers extract

这是我制作的代码:

public static boolean isOperator(char op){
    if (op == '+' || op == '-'
            || op == '*' || op == '/'
            || op == '^'
            || op == '(' || op == ')'){
        return true;
    }
    return false;
}

public static boolean isOperand(char op){
    String numbers = "0123456789.";
    int a = numbers.indexOf(op);
    return a >= 0;
}
public static void main(String []args){        
    String exp= "15+20+(3.84*25)*(78/3.8)";
    LinkedList a = new LinkedList();

    for (int i = 0; i < exp.length(); i++){
        if (isOperator(exp.charAt(i))){
            a.add(exp.charAt(i));
        } else if (isOperand(exp.charAt(i))){
            int k = i;
            while (k < exp.length()){//I see the length of the number
                if (isOperand(exp.charAt(k))){
                    k++;
                } else {
                    break;
                }
            }
            if (k != exp.length()-1){//if it's not ad the end
                a.add(exp.substring(i, k));
            } else {//if it's at the end I take all the remaining chars of the string
                a.add(exp.substring(i));
            }
            i = k-1;//i must go back since the subtring second parameter is exclusive
        } 
    }
    System.out.println(a);    
}//main
Run Code Online (Sandbox Code Playgroud)

这是输出:

[15, +, 20, +, (, 3.84, *, 25, ), *, (, 78, /, 3.8), )]
Run Code Online (Sandbox Code Playgroud)

这正是我想要的.如您所见,我将操作数和运算符分别放入维护字符串顺序的列表中.有一种方法可以更简单的方式吗?

Juv*_*nis 5

有没有办法以更简单的方式做到这一点?

就在这里.使用正则表达式.看看下面的代码,并尝试运行它来输入.

public static void main(String[] args) 
{
    String exp = "15+20+(3.84*25)*(78/3.8)";
    String regex = "(\\d+\\.\\d+)|(\\d+)|([+-/*///^])|([/(/)])";

    Matcher m = Pattern.compile(regex).matcher(exp);

    LinkedList list = new LinkedList();

    while (m.find()) {
        list.add(m.group());
    }

    System.out.println(list);
}
Run Code Online (Sandbox Code Playgroud)

我上面使用的正则表达式的解释:

"(\ d +\\ d +)|(\ d +)|([+ - /*/// ^])|([/(/)])"

(double)或(整数)或(算术运算符)或(左/右paranthesis)