Reputation: 25
I have string in java but not understand how to split these type of string using.
I have only arithmetic and logical operator .
char[] operators = new char[] { '\\', 'x', '+', '-', '>', '*','<', '=' };
String str_spit="usa_newyork=japan\london*44+jhon<last-987";
Actual String - >
String a= QN_770_0=QN_770_0\10
and
String b= QN_770_0>66
My Code:
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);
}
}
Error:
operators.toString()---->\
Exception in thread "main" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
\
^
Upvotes: 0
Views: 827
Reputation: 533660
I would use the Javascript engine to do this. It will not only parse the String but evalate it for you and much, much more.
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);
prints
false
Upvotes: 0
Reputation: 3060
Try using StringTokenizer
String delim = new String(operators);
StringTokenizer st = new StringTokenizer(str_spit, delim);
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
Upvotes: 2