Search code examples
javaregexcapture-group

java regex split string with white space(except when both left and right was number or - )


I have this string how to split 5-28 14:00 - 5-28 18:00 the60s(.corp). I want to split it with white space except when the white space have number or - around them.

The result I want was:

1. how 
2. to
3. split
4. 5-28 14:00 - 5-28 18:00
5. the60s(.corp)

Thanks.

The following is my code:

String str = "how do I split 5-28 14:00 - 5-28 18:00 the60s(.corp)";
    str = str.replaceAll("\\s+(?!(?=-|\\d+))", "@");

First I replace the right white space with @ , then split the string with @. But it doesn't work.


Solution

  • You can use lookarounds for this:

    (?<![-\d])\s+|\s+(?![\d-])
    

    Code Demo