Java String.split("\\s+")

19.3k Views Asked by At

I am trying to parse some output. The output is as follows:

raidz1-0 ONLINE 0 0 0

My code is as follows:

String line = "\traidz1-0  ONLINE       0     0     0";
String[] tokens = line.split("\\s+");

tokens ends up being {"raidz1-0", "ONLINE", "0"}

For some reason the last 2 zeros are discarded. I would like to retain the zeros, please tell me how.

2

There are 2 best solutions below

2
Rohit Jain On BEST ANSWER

Well, it works fine in my case, and it should work: -

String line = "\traidz1-0  ONLINE       0     0     0";
String[] tokens = line.split("\\s+");

System.out.println(Arrays.toString(tokens));

OUTPUT : -

[, raidz1-0, ONLINE, 0, 0, 0]

Are you sure, you didn't get the last two zeros?

0
jlordo On

This code:

String line = "\traidz1-0  ONLINE       0     0     0";
String[] tokens = line.split("\\s+");
System.out.println(tokens.length);
System.out.println(Arrays.toString(tokens));

prints:

    6
    [, raidz1-0, ONLINE, 0, 0, 0]