如何在java中拆分字符串中的多个运算符

时间:2014-05-02 09:20:58

标签: java

我在java中有字符串,但不明白如何使用。分割这些类型的字符串。

我只有 算术和逻辑运算符

 char[] operators = new char[] { '\\', 'x', '+', '-', '>', '*','<', '=' };
  String str_spit="usa_newyork=japan\london*44+jhon<last-987";

实际字符串 - &gt;

 String a= QN_770_0=QN_770_0\10

 String b= QN_770_0>66

我的代码:

ArrayList <String> logics;
        ArrayList <String>  logicQuestions = null;

        char[] operators = new char[] { '\\', 'x', '+', '-', '>', '<', '=' };   

        String str_spit="QN_770_0=QN_770_0\10";
         for ( jj = 0; jj < operators.length; jj++)
         {
        System.out.println("operators.toString()---->"+operators[jj]);
        //String[] questions = logicText.split(operators);
         String s = "" + operators[jj];
        String[] questions=str_spit.split(s);
        System.out.println("questions questions---->"+questions);
        //for each segment, save all question codes. 
        for (int j = 0; j < questions.length; j++)
        {
         String question = questions[j];
         System.out.println("questions questions---question->"+questions);
            if (question.startsWith("QN_") && !logicQuestions.contains(question))
                logicQuestions.add(question);
            System.out.println("logicQuestions---logicQuestions->"+logicQuestions);
        }

         }

错误:

operators.toString()---->\
Exception in thread "main" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
\
 ^

2 个答案:

答案 0 :(得分:2)

尝试使用StringTokenizer

    String delim = new String(operators);    
    StringTokenizer st = new StringTokenizer(str_spit, delim);
    while (st.hasMoreTokens()) {
        System.out.println(st.nextToken());
    }

答案 1 :(得分:0)

我会使用Javascript引擎来执行此操作。它不仅会解析字符串,而且会为你和其他更多的东西进行分析。

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("nashorn");
ScriptContext context = new SimpleScriptContext();
int scope = context.getScopes().get(0);
context.setAttribute("japan", 100, scope);
context.setAttribute("london", 10, scope);
context.setAttribute("jhon", -10, scope);
context.setAttribute("last", 1000, scope);

String str = "usa_newyork= japan / london * 44 + jhon < last - 987";

Object usa_newyork = engine.eval(str, context);
System.out.println(usa_newyork);

打印

false