如何在Java中标记该字符串? [英] How can tokenize this string in java?

查看:53
本文介绍了如何在Java中标记该字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将这些简单的数学表达式拆分为单独的字符串?

How can I split these simple mathematical expressions into seperate strings?

我知道我基本上想使用正则表达式:"[0-9] + | [* +-^()]" ,但看来String.split()不会之所以起作用,是因为它也消耗了定界符.

I know that I basically want to use the regular expression: "[0-9]+|[*+-^()]" but it appears String.split() won't work because it consumes the delimiter tokens as well.

我希望它拆分所有整数:0-9,以及所有运算符* +-^().

I want it to split all integers: 0-9, and all operators *+-^().

所以, 578 + 223-5 ^ 2

将被分为:

578  
+  
223  
-  
5  
^  
2  

做到这一点的最佳方法是什么?

What is the best approach to do that?

推荐答案

横向来看,并假设您的最终目的是用数学方法评估String,那么最好使用ScriptEngine

Going at this laterally, and assuming your intention is ultimately to evaluate the String mathematically, you might be better off using the ScriptEngine

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class Evaluator {
private ScriptEngineManager sm = new ScriptEngineManager();
private ScriptEngine sEngine = sm.getEngineByName("js");

public double stringEval(String expr)
{
Object res = "";
        try {
           res = sEngine.eval(expr);
          }
         catch(ScriptException se) {
            se.printStackTrace();
        }
        return Double.parseDouble( res.toString());
}

}

然后您可以拨打以下电话:

Which you can then call as follows:

Evaluator evr = new Evaluator();  
String sTest = "+1+9*(2 * 5)";  
double dd = evr.stringEval(sTest);  
System.out.println(dd); 

在数学上评估String时,我走了这条路,不是很多运算符会在正则表达式中杀死您,而是复杂的嵌套方括号表达式.不重新发明轮子是a)更安全b)更快并且c)意味着不需要维护的复杂代码和嵌套代码.

I went down this road when working on evaluating Strings mathematically and it's not so much the operators that will kill you in regexps but complex nested bracketed expressions. Not reinventing the wheel is a) safer b) faster and c) means less complex and nested code to maintain.

这篇关于如何在Java中标记该字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆