How to split a line with space characters at the beginning?

Quick example:

public class Test { public static void main(String[] args) { String str = " ab"; String[] arr = str.split("\\s+"); for (String s : arr) System.out.println(s); } } 

I want the arr array to contain 2 elements: "a" and "b", but as a result there are 3 elements: "" (empty string), "a" and "b". What should I do to understand this?

+7
source share
4 answers

Kind of cheating, but replace:

 String str = " ab"; 

from

 String str = " ab".trim(); 
+4
source

Another way to crop this is to use a look ahead and look to make sure that the space is sandwiched between two characters without space, ... something like:

 String[] arr = str.split("(?<=\\S)\\s+(?=\\S)"); 

The problem is that it does not clip the leading spaces, giving this result:

  a b 

but it should not be used as String#split(...) for splitting, not for trimming.

+2
source

A simple solution is to use trim() to remove the leading (and trailing) space before calling split(...) .

You cannot do this only with split(...) . A separable regular expression matches line breaks; that is, there will necessarily be a substring (possibly empty) before and after each agreed separator.

You can deal with the case when the space ends with split(..., 0) . This discards any trailing blank lines. However, there is no equivalent split form to discard leading blank lines.

+1
source

Instead of trimming, you can simply add if to check if the string is empty or not.

0
source

All Articles