How to split a string with whitespace chars at the beginning?

后端 未结 4 789
青春惊慌失措
青春惊慌失措 2021-01-12 14:43

Quick example:

public class Test {
    public static void main(String[] args) {
        String str = \"   a b\";
        String[] arr = str.split(\"\\\\s+\")         


        
4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-12 15:23

    The other way to trim it is to use look ahead and look behind to be sure that the whitespace is sandwiched between two non-white-space characters,... something like:

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

    The problem with this is that it doesn't trim the leading spaces, giving this result:

       a
    b
    

    but nor should it as String#split(...) is for splitting, not trimming.

提交回复
热议问题