Beginner
Beginner

Reputation: 69

Java split by \\S

I am doing some study about regex. I tried with

public static void main(String[] agrs) {

    String s = "I am preparing ocp";
    String[] tokens = s.split("\\S");
    System.out.println(tokens.length);
    for (String x : tokens) {
        System.out.println(x);
    }
}

and the result shown is 13 whitespaces.

However, when I add a whitespace behind the string as below,

public static void main(String[] agrs) {

    String s = "I am preparing ocp ";
    String[] tokens = s.split("\\S");
    System.out.println(tokens.length);
    for (String x : tokens) {
        System.out.println(x);
    }
}

the result will be 16.

I dont quite understand how this regex works in this situation..anyone can enlighten me?

Upvotes: 2

Views: 656

Answers (1)

Jim Garrison
Jim Garrison

Reputation: 86774

You want to split on \\s (lowercase s) instead of uppercase s.

The way you have it now you are saying non-whitespace characters are delimiters, leaving nothing but whitespace as your "data".

Also, it should probably be \\s+ to allow multiple contiguous spaces as delimiters.

Upvotes: 5

Related Questions