Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guava Splitter with multiple split parameters

Tags:

java

split

guava

Playing with Guava I can either set the split to be a single character, a string or a regular expression.

What I want is to split on multiple inputs without having to resort to using regular expressions as I want to built up the separators using method calls.

What I'm trying to do is to get it to let me do something like:

Splitter.on(',')
    .on('.')
    .on('|')
    .on("BREAK")
    .splitToList(test);

So for the input "a,b,c.d|e BREAK f" would produce a list containing a/b/c/d/e/f.

This is done within a class I'm writing so maybe construct a regular expression from the inputs when the call is made to finally process the data and use this as the one and only .on() call?

Thanks.

like image 502
Neil Walker Avatar asked Jan 13 '14 19:01

Neil Walker


People also ask

How do you split a string with multiple delimiters?

Using String. split() Method. The split() method of the String class is used to split a string into an array of String objects based on the specified delimiter that matches the regular expression.

How do you pass multiple delimiters in Java?

We just have to define an input string we want to split and a pattern. The next step is to apply a pattern. A pattern can match zero or multiple times. To split by different delimiters, we should just set all the characters in the pattern.

What is splitter in Java?

Guava's Splitter Class provides various methods to handle splitting operations on string, objects, etc. It extracts non-overlapping substrings from an input string, typically by recognizing appearances of a separator sequence.


1 Answers

As @Louis Wasserman pointed out, you want to use a regular expression here. You can either use Splitter.on(Pattern) or Splitter.onPattern(String) to accomplish this, and construct a regular expression to match the separators, like ([,.|]|BREAK).

Here is my method with a test. This test fails for the CharMatcher approach, and succeeds with the regular expression.

public class SplitterTest {
    public String splitAndRejoin(String pre) {
        return Joiner.on("/").join(
            Splitter
                .onPattern("([,.|]|BREAK)")
                .trimResults()
                .omitEmptyStrings()
                .split(pre));
    }

    @Test
    public void test1() {
        assertEquals("a/b/c/d/e/f", splitAndRejoin("a,b,c.d|e BREAK f"));
        assertEquals("A/B/C/D/E/F", splitAndRejoin("A,B,C.D|E BREAK F"));
    }
}
like image 147
Ray Avatar answered Oct 14 '22 21:10

Ray