Split string and trim every element

后端 未结 5 949
失恋的感觉
失恋的感觉 2021-02-01 14:39

Is there any library API or regex pattern to split a String on some delimiter and automatically trim leading and trailing spaces from every element without having to loop the el

5条回答
  •  情话喂你
    2021-02-01 15:15

    Guava to the rescue! Use CharMatcher and Splitter. I use Joiner just to stitch the Iterable back together, clearly showing that the iterable only has the letters in it, with no padding, extraneous spaces, or hash signs.

    package main;
    
    import com.google.common.base.CharMatcher;
    import com.google.common.base.Joiner;
    import com.google.common.base.Splitter;
    
    public class TestMain {
    
        static Splitter split = Splitter.on(CharMatcher.anyOf(" #")).trimResults()
                .omitEmptyStrings();
        static Joiner join = Joiner.on(", ");
    
        public static void main(String[] args) {
            final String test = " A B # C#D# E # ";
            System.out.println(join.join(split.split(test)));
        }
    }
    

    Output:

    A, B, C, D, E
    

    Great for people who get headaches from regex.

提交回复
热议问题