Search code examples
javastringsplitdelimiter

java split string with scanner not losing delimiters


I got sentences like

"Peter Tosh  and Mary Miller  or Michael or Stephan and Andrea Kurnikova"

and want to split them either on and or or

When I am using the code:

Scanner fromStr = new Scanner("Peter Tosh  and Mary Miller  or Michael or Stephan and Andrea Kurnikova");
fromStr.useDelimiter(" and | or ");
while (fromStr.hasNext()) {
    String temp = fromStr.next();
    System.out.println(temp);
}

The result is:

Peter Tosh 
Mary Miller 
Michael
Stephan
Andrea Kurnikova

But I need the following (not losing the delimiter value):

Peter Tosh 
and Mary Miller 
or Michael
or Stephan
and Andrea Kurnikova

Please consider that the and/or can differ from sentence to sentence. With other words, it has to be dynamic.


Solution

  • Why you are using Scanner and all that loop? you can just use String::split which take a regex, and you can use this regex (?=and|or) to split :

    String str = "Peter Tosh  and Mary Miller  or Michael or Stephan and Andrea Kurnikova";
    String[] split = str.split("(?=and|or)");
    Arrays.asList(split).forEach(System.out::println);
    

    Outputs:

    Peter Tosh  
    and Mary Miller  
    or Michael 
    or Stephan 
    and Andrea Kurnikova