java - String.split() at a meta character + -


i'm making simple program deal equations string input of equation when run it, however, exception because of trying replace " +" " +" can split string @ spaces. how should go using

the string replaceall method replace these special characters? below code

exception in thread "main" java.util.regex.patternsyntaxexception: dangling meta character '+' near index 0 + ^

 public static void parse(string x){        string z = "x^2+2=2x-1";         string[] lrside =  z.split("=",4);        system.out.println("left side: " + lrside[0] + " / right side: " + lrside[1]);        string rightside = lrside[0];        string leftside = lrside[1];         rightside.replaceall("-", " -");        rightside.replaceall("+", " +");        leftside.replaceall("-", " -"); leftside.replaceall("+", " +");        list<string> rightt = arrays.aslist(rightside.split(" "));        list<string> leftt = arrays.aslist(leftside.split(" "));         system.out.println(leftt);        system.out.println(rightt); 

replaceall accepts regular expression first argument.

+ special character denotes quantifier meaning one or more occurrences. therefore should escaped specify literal character +:

rightside = rightside.replaceall("\\+", " +"); 

(strings immutable necessary assign variable result of replaceall);

an alternative use character class removes metacharacter status:

rightside = rightside.replaceall("[+]", " +"); 

the simplest solution though use replace method uses non-regex string literals:

rightside = rightside.replace("+", " +");  

Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

c# - Attempting to upload to FTP: System.Net.WebException: System error -

ios - UISlider customization: how to properly add shadow to custom knob image -