Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a String using Word Delimiters

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.

like image 725
jch Avatar asked Jun 08 '11 21:06

jch


People also ask

How do you split a string with a delimiter?

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.

How do I split a string in Word?

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.


2 Answers

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
like image 158
jeffb Avatar answered Sep 28 '22 15:09

jeffb


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.

like image 23
Romain Hippeau Avatar answered Sep 28 '22 14:09

Romain Hippeau