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
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
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.
What about just doing a replaceall before splitting?
str.replaceall("\\s*#\\s*","#").split()
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/
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"]