繁体   English   中英

从字符串中提取数字和运算符

[英]Extract numbers and operators from a String

这是我编写的代码:

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

这是输出:

[15, +, 20, +, (, 3.84, *, 25, ), *, (, 78, /, 3.8), )]

这正是我想要的。 如您所见,我将操作数和运算符分别放入一个列表中,以保持字符串的顺序。 有没有一种方法可以更简单地做到这一点?

有没有一种方法可以更简单地做到这一点?

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

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);
}

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

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

(双精度)或(整数)或(算术运算符)或(左/右括号)

进行此类解析工作的最佳方法是使用解析器生成器。 但是,如果您想自己做,则有多种选择。 在这种情况下,您也可以按照以下方式进行操作:

  public static void main(String[] args) throws Exception{ 
      String exp = "15+20+(3.84*25)*(78/3.8)";
      LinkedList<String> a = new LinkedList<String>();

      StringTokenizer st = new StringTokenizer(exp, "+*/-()", true);
      while(st.hasMoreTokens())
          a.add(st.nextToken());
    } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM