Split string by word contain space in Java

Viewed 38

I have a String pattern: "hh:mm:ss dd:MM:yyyy to hh:mm:ss dd:MM:yyyy" and I want to extract date String from it.

Example:

S = "00:00:00 19/08/2022 to 23:59:59 19/08/2022"

Split into S1 = "00:00:00 19/08/2022" and S2 = "23:59:59 19/08/2022".

I'm trying to use String.split function but can't figure out the regex yet. Can somebody help?

I'm using Java 8.

1 Answers

Just split on \s+to\s+:

String pattern = "00:00:00 19/08/2022 to 23:59:59 19/08/2022";
String[] parts = pattern.split("\\s+to\\s+");
System.out.println(Arrays.toString(parts));

This prints:

[00:00:00 19/08/2022, 23:59:59 19/08/2022]
Related