Split string and trim every element

后端 未结 5 943
失恋的感觉
失恋的感觉 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:10

    Just trim it before you split

    " A B # C#D# E # ".trim().split("\\s*#\\s*")
    

    The spaces after the commas in [ A B, C, D, E] are just the way Arrays.toString prints

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-01 15:21

    What about just doing a replaceall before splitting?

    str.replaceall("\\s*#\\s*","#").split()
    
    0 讨论(0)
  • 2021-02-01 15:22

    Edited to correct whitespace error that was pointed out by Marcus.

    I think that the proper regex should be [\s]*#[\s]*:

    str.split("[\\s]*#[\\s]*");
    

    Tested on : http://regexpal.com/

    0 讨论(0)
  • 2021-02-01 15:27

    Without regex it should look like this:

    "  A   B #  C#D# E  #  "
        .split('#')
        .map(function(item) { return item.trim(); } )
        .filter(function(n){ return n != "" });
    

    outputs: ["A B", "C", "D", "E"]

    0 讨论(0)
提交回复
热议问题