1

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.

1 Answer 1

4

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
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.