3

This question answers how we can split a string using multiple delimiters? Is it also possible to split a String using multiple keywords.

For example:

String myString = (One Two Three) AND (Four Five Six) OR (Six Seven Eight)

And I want to split myString at both AND and OR so that I get:

  someArray[0] = (One Two Three)

  someArray[1] = (Four Five Six)

  someArray[2] = (Six Seven Eight)

I do not know much of regex, so any help or advice would be helpful. Thanks in advance.

Community
  • 1
  • 1
Anjan Baradwaj
  • 1,219
  • 5
  • 27
  • 54
  • It looks like you are trying to process an expression of sorts. If that is the case, using a simple `split` will prove too limiting very soon (specifically, when you add a second level of parentheses). Consider switching your approach to something more robust - say, a simple recursive descent parser. – Sergey Kalinichenko Jun 17 '14 at 11:19
  • @dasblinkenlight a simple recursive descent parser? My knowledge is limited on that. Could you be more elaborate? – Anjan Baradwaj Jun 17 '14 at 11:21
  • You can read more about recursive descent parsers on wikipedia. They could be really small - here is a [link to a tutorial](http://math.hws.edu/javanotes/c9/s5.html) explaining how to write a small but useable recursive descent parser that understands expressions with arbitrary level of parentheses. – Sergey Kalinichenko Jun 17 '14 at 11:30

2 Answers2

4

Try this :

String[] someArray=yourString.split("(AND)|(OR)");
Mifmif
  • 3,132
  • 18
  • 23
3
public static void main(String[] args) {
    String s = "(One Two Three) AND (Four Five Six) OR (Six Seven Eight)";
    System.out.println(Arrays.toString(s.split("(AND|OR)")));

}

O/P :

[(One Two Three) ,  (Four Five Six) ,  (Six Seven Eight)]
TheLostMind
  • 35,966
  • 12
  • 68
  • 104