Using regex to split Java string for multiple whitespaces

Let’s say you have a string –

String s = “Must     have  some         room.”

As you see, the whitespaces are not constant.

We can split this up using a regex string:

String delim = “\\s{1,}”;
String[] arr = s.split(delim);
for (int i=0;i<arr.length;i++)
System.out.println(arr[i]);

Where “\\s” is regex for whitespace, and adding “{1,}” tells that it can range from 1 to any greater value.
Thus all splits are taken care of.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s