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
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.