i have a string as below
a > b and c < d or d > e and f > g
outcome must be:
a > b
and
c < d
or
d > e
and
f > g
i want to split the string at occurrences of "and" , "or" and retrieve the delims as well along with the token.[i need them in order to evaluate the expression]
i tried using StringTokenizer as
new StringTokenizer(x, "\\sand\\s|\\sor\\s", true);
but i dont get desired outcome. i tried using scanner as
Scanner sc = new Scanner(x);
sc.useDelimiter("and | or");
this is able to split but doesnt return the delimiters.
please suggest.
i have given a , b , c above but there cud be words instead of a,b , c with spaces. Updated example.
You can use the split() method of String class from JDK to split a String based on a delimiter e.g. splitting a comma-separated String on a comma, breaking a pipe-delimited String on a pipe, or splitting a pipe-delimited String on a pipe.
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.
This will split on "and" or "or" with any number of spaces surrounding the words.
String test = "2 < 3 and 3 > 2 or 4 < 6 and 7 < 8";
String [] splitString = test.split("\\s*[and|or]+\\s*");
for(int i = 0; i < splitString.length ; i ++){
System.out.println(splitString[i]);
}
output
2 < 3
3 > 2
4 < 6
7 < 8
What you really want is a tool like JFlex by the time you run into all the different permutations of white spaces and as your syntax grows. In the long run you will save time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With