Take the 2-minute tour ×

i have a string as below

a > b and c < d or d > e and f > g

outcome must be:

a > b
c < d
d > e
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.

share|improve this question
Your description implies using the Strings "and" & "or" as delimiters, but your output implies " " as a delimiter. Please clarify. –  djg Jun 8 '11 at 21:43
doh! i give bad example as string..let me provide another example –  jch Jun 8 '11 at 21:45
add comment

4 Answers

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.

share|improve this answer
add comment
String delim = " ";
String[] splitstrings = yourString.split(delim);
for (int i = 0; i < splitstrings.length(); i++) {
    splitstrings += delim;
share|improve this answer
OP wants the delims to be returned as well. split wont return delims. –  CoolBeans Jun 8 '11 at 21:41
i ddint explain clearly..i have updated the example now. –  jch Jun 8 '11 at 21:48
sorry, but i dont think thats right.. –  jch Jun 8 '11 at 21:57
add comment

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 ++){


2 < 3
3 > 2
4 < 6
7 < 8
share|improve this answer
how to get the delimiter as well ? –  jch Jun 8 '11 at 22:34
add comment

A StringTokenizer is the only java standard class that is capable of returning the used delimiter as well as far as I'm aware. Just copied the regex from the OT assuming that it'll do what he wants (which on second glance I extremely doubt from his textual description, but oh well - just insert the right one)

    String input = "a > b and c < d or d > e and f > g";
    StringTokenizer tokenizer = new StringTokenizer(input, "\\sand\\s|\\sor\\s", true);
    while (tokenizer.hasMoreTokens()) {
share|improve this answer
add comment

Your Answer


