Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2009 The Guava Authors
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package com.google.common.base;
 
 import static com.google.common.base.Preconditions.checkArgument;
 import static com.google.common.base.Preconditions.checkNotNull;
 
 
 import java.util.List;
 import java.util.Map;
 
 import  javax.annotation.CheckReturnValue;

Extracts non-overlapping substrings from an input string, typically by recognizing appearances of a separator sequence. This separator can be specified as a single character, fixed on(String) string, regular expression or on(CharMatcher) CharMatcher instance. Or, instead of using a separator at all, a splitter can extract adjacent substrings of a given fixedLength fixed length.

For example, this expression:

   Splitter.on(',').split("foo,bar,qux")
... produces an Iterable containing "foo", "bar" and "qux", in that order.

By default, Splitter's behavior is simplistic and unassuming. The following expression:

   Splitter.on(',').split(" foo,,,  bar ,")
... yields the substrings [" foo", "", "", " bar ", ""]. If this is not the desired behavior, use configuration methods to obtain a new splitter instance with modified behavior:
   private static final Splitter MY_SPLITTER = Splitter.on(',')
       .trimResults()
       .omitEmptyStrings();

Now MY_SPLITTER.split("foo,,, bar ,") returns just ["foo", "bar"]. Note that the order in which these configuration methods are called is never significant.

Warning: Splitter instances are immutable. Invoking a configuration method has no effect on the receiving instance; you must store and use the new splitter instance it returns instead.

   // Do NOT do this
   Splitter splitter = Splitter.on('/');
   splitter.trimResults(); // does nothing!
   return splitter.split("wrong / wrong / wrong");

For separator-based splitters that do not use omitEmptyStrings, an input string containing n occurrences of the separator naturally yields an iterable of size n + 1. So if the separator does not occur anywhere in the input, a single substring is returned containing the entire input. Consequently, all splitters split the empty string to [""] (note: even fixed-length splitters).

Splitter instances are thread-safe immutable, and are therefore safe to store as static final constants.

The Joiner class provides the inverse operation to splitting, but note that a round-trip between the two should be assumed to be lossy.

See the Guava User Guide article on Splitter.

Author(s):
Julien Silland
Jesse Wilson
Kevin Bourrillion
Louis Wasserman
Since:
1.0
@GwtCompatible(emulated = true)
public final class Splitter {
  private final CharMatcher trimmer;
  private final boolean omitEmptyStrings;
  private final Strategy strategy;
  private final int limit;
  private Splitter(Strategy strategy) {
    this(strategyfalse..);
  }
  private Splitter(Strategy strategyboolean omitEmptyStrings,
      CharMatcher trimmerint limit) {
    this. = strategy;
    this. = omitEmptyStrings;
    this. = trimmer;
    this. = limit;
  }

  
Returns a splitter that uses the given single-character separator. For example, Splitter.on(',').split("foo,,bar") returns an iterable containing ["foo", "", "bar"].

Parameters:
separator the character to recognize as a separator
Returns:
a splitter, with default settings, that recognizes that separator
  public static Splitter on(char separator) {
    return on(CharMatcher.is(separator));
  }

  
Returns a splitter that considers any single character matched by the given CharMatcher to be a separator. For example, Splitter.on(CharMatcher.anyOf(";,")).split("foo,;bar,quux") returns an iterable containing ["foo", "", "bar", "quux"].

Parameters:
separatorMatcher a CharMatcher that determines whether a character is a separator
Returns:
a splitter, with default settings, that uses this matcher
  public static Splitter on(final CharMatcher separatorMatcher) {
    checkNotNull(separatorMatcher);
    return new Splitter(new Strategy() {
      @Override public SplittingIterator iterator(
          Splitter splitterfinal CharSequence toSplit) {
        return new SplittingIterator(splittertoSplit) {
          @Override int separatorStart(int start) {
            return separatorMatcher.indexIn(start);
          }
          @Override int separatorEnd(int separatorPosition) {
            return separatorPosition + 1;
          }
        };
      }
    });
  }

  
Returns a splitter that uses the given fixed string as a separator. For example, Splitter.on(", ").split("foo, bar,baz") returns an iterable containing ["foo", "bar,baz"].

Parameters:
separator the literal, nonempty string to recognize as a separator
Returns:
a splitter, with default settings, that recognizes that separator
  public static Splitter on(final String separator) {
    checkArgument(separator.length() != 0,
        "The separator may not be the empty string.");
    return new Splitter(new Strategy() {
      @Override public SplittingIterator iterator(
          Splitter splitterCharSequence toSplit) {
        return new SplittingIterator(splittertoSplit) {
          @Override public int separatorStart(int start) {
            int delimeterLength = separator.length();
            positions:
            for (int p = startlast = .length() - delimeterLength;
                p <= lastp++) {
              for (int i = 0; i < delimeterLengthi++) {
                if (.charAt(i + p) != separator.charAt(i)) {
                  continue positions;
                }
              }
              return p;
            }
            return -1;
          }
          @Override public int separatorEnd(int separatorPosition) {
            return separatorPosition + separator.length();
          }
        };
      }
    });
  }

  
Returns a splitter that considers any subsequence matching pattern to be a separator. For example, Splitter.on(Pattern.compile("\r?\n")).split(entireFile) splits a string into lines whether it uses DOS-style or UNIX-style line terminators.

Parameters:
separatorPattern the pattern that determines whether a subsequence is a separator. This pattern may not match the empty string.
Returns:
a splitter, with default settings, that uses this pattern
Throws:
IllegalArgumentException if separatorPattern matches the empty string
  @GwtIncompatible("java.util.regex")
  public static Splitter on(final Pattern separatorPattern) {
    checkNotNull(separatorPattern);
    checkArgument(!separatorPattern.matcher("").matches(),
        "The pattern may not match the empty string: %s"separatorPattern);
    return new Splitter(new Strategy() {
      @Override public SplittingIterator iterator(
          final Splitter splitterCharSequence toSplit) {
        final Matcher matcher = separatorPattern.matcher(toSplit);
        return new SplittingIterator(splittertoSplit) {
          @Override public int separatorStart(int start) {
            return matcher.find(start) ? matcher.start() : -1;
          }
          @Override public int separatorEnd(int separatorPosition) {
            return matcher.end();
          }
        };
      }
    });
  }

  
Returns a splitter that considers any subsequence matching a given pattern (regular expression) to be a separator. For example, Splitter.onPattern("\r?\n").split(entireFile) splits a string into lines whether it uses DOS-style or UNIX-style line terminators. This is equivalent to Splitter.on(Pattern.compile(pattern)).

Parameters:
separatorPattern the pattern that determines whether a subsequence is a separator. This pattern may not match the empty string.
Returns:
a splitter, with default settings, that uses this pattern
Throws:
java.util.regex.PatternSyntaxException if separatorPattern is a malformed expression
IllegalArgumentException if separatorPattern matches the empty string
  @GwtIncompatible("java.util.regex")
  public static Splitter onPattern(String separatorPattern) {
    return on(Pattern.compile(separatorPattern));
  }

  
Returns a splitter that divides strings into pieces of the given length. For example, Splitter.fixedLength(2).split("abcde") returns an iterable containing ["ab", "cd", "e"]. The last piece can be smaller than length but will never be empty.

Exception: for consistency with separator-based splitters, split("") does not yield an empty iterable, but an iterable containing "". This is the only case in which Iterables.size(split(input)) does not equal IntMath.divide(input.length(), length, CEILING). To avoid this behavior, use omitEmptyStrings.

Parameters:
length the desired length of pieces after splitting, a positive integer
Returns:
a splitter, with default settings, that can split into fixed sized pieces
Throws:
IllegalArgumentException if length is zero or negative
  public static Splitter fixedLength(final int length) {
    checkArgument(length > 0, "The length may not be less than 1");
    return new Splitter(new Strategy() {
      @Override public SplittingIterator iterator(
          final Splitter splitterCharSequence toSplit) {
        return new SplittingIterator(splittertoSplit) {
          @Override public int separatorStart(int start) {
            int nextChunkStart = start + length;
            return (nextChunkStart < .length() ? nextChunkStart : -1);
          }
          @Override public int separatorEnd(int separatorPosition) {
            return separatorPosition;
          }
        };
      }
    });
  }

  
Returns a splitter that behaves equivalently to this splitter, but automatically omits empty strings from the results. For example, Splitter.on(',').omitEmptyStrings().split(",a,,,b,c,,") returns an iterable containing only ["a", "b", "c"].

If either trimResults option is also specified when creating a splitter, that splitter always trims results first before checking for emptiness. So, for example, Splitter.on(':').omitEmptyStrings().trimResults().split(": : : ") returns an empty iterable.

Note that it is ordinarily not possible for split(CharSequence) to return an empty iterable, but when using this option, it can (if the input sequence consists of nothing but separators).

Returns:
a splitter with the desired configuration
  @CheckReturnValue
  public Splitter omitEmptyStrings() {
    return new Splitter(true);
  }

  
Returns a splitter that behaves equivalently to this splitter but stops splitting after it reaches the limit. The limit defines the maximum number of items returned by the iterator.

For example, Splitter.on(',').limit(3).split("a,b,c,d") returns an iterable containing ["a", "b", "c,d"]. When omitting empty strings, the omitted strings do no count. Hence, Splitter.on(',').limit(3).omitEmptyStrings().split("a,,,b,,,c,d") returns an iterable containing ["a", "b", "c,d". When trim is requested, all entries, including the last are trimmed. Hence Splitter.on(',').limit(3).trimResults().split(" a , b , c , d ") results in

Parameters:
limit the maximum number of items returns
Returns:
a splitter with the desired configuration
Since:
9.0
:
code ["a", "b", "c , d"]}.
  @CheckReturnValue
  public Splitter limit(int limit) {
    checkArgument(limit > 0, "must be greater than zero: %s"limit);
    return new Splitter(limit);
  }

  
Returns a splitter that behaves equivalently to this splitter, but automatically removes leading and trailing CharMatcher.WHITESPACE whitespace from each returned substring; equivalent to trimResults(CharMatcher.WHITESPACE). For example, Splitter.on(',').trimResults().split(" a, b ,c ") returns an iterable containing ["a", "b", "c"].

Returns:
a splitter with the desired configuration
  @CheckReturnValue
  public Splitter trimResults() {
  }

  
Returns a splitter that behaves equivalently to this splitter, but removes all leading or trailing characters matching the given CharMatcher from each returned substring. For example, Splitter.on(',').trimResults(CharMatcher.is('_')).split("_a ,_b_ ,c__") returns an iterable containing ["a ", "b_ ", "c"].

Parameters:
trimmer a CharMatcher that determines whether a character should be removed from the beginning/end of a subsequence
Returns:
a splitter with the desired configuration
  // TODO(kevinb): throw if a trimmer was already specified!
  @CheckReturnValue
  public Splitter trimResults(CharMatcher trimmer) {
    checkNotNull(trimmer);
    return new Splitter(trimmer);
  }

  
Splits sequence into string components and makes them available through an Iterator, which may be lazily evaluated. If you want an eagerly computed List, use splitToList(CharSequence).

Parameters:
sequence the sequence of characters to split
Returns:
an iteration over the segments split from the parameter.
  public Iterable<Stringsplit(final CharSequence sequence) {
    checkNotNull(sequence);
    return new Iterable<String>() {
      @Override public Iterator<Stringiterator() {
        return spliterator(sequence);
      }
      @Override public String toString() {
        return Joiner.on(", ")
            .appendTo(new StringBuilder().append('['), this)
            .append(']')
            .toString();
      }
    };
  }
  private Iterator<Stringspliterator(CharSequence sequence) {
    return .iterator(thissequence);
  }

  
Splits sequence into string components and returns them as an immutable list. If you want an Iterable which may be lazily evaluated, use split(CharSequence).

Parameters:
sequence the sequence of characters to split
Returns:
an immutable list of the segments split from the parameter
Since:
15.0
  @Beta
  public List<StringsplitToList(CharSequence sequence) {
    checkNotNull(sequence);
    Iterator<Stringiterator = spliterator(sequence);
    List<Stringresult = new ArrayList<String>();
    while (iterator.hasNext()) {
      result.add(iterator.next());
    }
    return Collections.unmodifiableList(result);
  }

  
Returns a MapSplitter which splits entries based on this splitter, and splits entries into keys and values using the specified separator.

Since:
10.0
  @CheckReturnValue
  @Beta
  public MapSplitter withKeyValueSeparator(String separator) {
    return withKeyValueSeparator(on(separator));
  }

  
Returns a MapSplitter which splits entries based on this splitter, and splits entries into keys and values using the specified separator.

Since:
14.0
  @CheckReturnValue
  @Beta
  public MapSplitter withKeyValueSeparator(char separator) {
    return withKeyValueSeparator(on(separator));
  }

  
Returns a MapSplitter which splits entries based on this splitter, and splits entries into keys and values using the specified key-value splitter.

Since:
10.0
  @CheckReturnValue
  @Beta
  public MapSplitter withKeyValueSeparator(Splitter keyValueSplitter) {
    return new MapSplitter(thiskeyValueSplitter);
  }

  
An object that splits strings into maps as Splitter splits iterables and lists. Like Splitter, it is thread-safe and immutable.

Since:
10.0
  @Beta
  public static final class MapSplitter {
    private static final String INVALID_ENTRY_MESSAGE =
        "Chunk [%s] is not a valid entry";
    private final Splitter outerSplitter;
    private final Splitter entrySplitter;
    private MapSplitter(Splitter outerSplitterSplitter entrySplitter) {
      this. = outerSplitter// only "this" is passed
      this. = checkNotNull(entrySplitter);
    }

    
Splits sequence into substrings, splits each substring into an entry, and returns an unmodifiable map with each of the entries. For example, Splitter.on(';').trimResults().withKeyValueSeparator("=>") .split("a=>b ; c=>b") will return a mapping from "a" to "b" and "c" to b.

The returned map preserves the order of the entries from sequence.

Throws:
IllegalArgumentException if the specified sequence does not split into valid map entries, or if there are duplicate keys
    public Map<StringStringsplit(CharSequence sequence) {
      Map<StringStringmap = new LinkedHashMap<StringString>();
      for (String entry : .split(sequence)) {
        Iterator<StringentryFields = .spliterator(entry);
        checkArgument(entryFields.hasNext(), entry);
        String key = entryFields.next();
        checkArgument(!map.containsKey(key), "Duplicate key [%s] found."key);
        checkArgument(entryFields.hasNext(), entry);
        String value = entryFields.next();
        map.put(keyvalue);
        checkArgument(!entryFields.hasNext(), entry);
      }
      return Collections.unmodifiableMap(map);
    }
  }
  private interface Strategy {
    Iterator<Stringiterator(Splitter splitterCharSequence toSplit);
  }
  private abstract static class SplittingIterator extends AbstractIterator<String> {
    final CharSequence toSplit;
    final CharMatcher trimmer;
    final boolean omitEmptyStrings;

    
Returns the first index in toSplit at or after start that contains the separator.
    abstract int separatorStart(int start);

    
Returns the first index in toSplit after separatorPosition that does not contain a separator. This method is only invoked after a call to separatorStart.
    abstract int separatorEnd(int separatorPosition);
    int offset = 0;
    int limit;
    protected SplittingIterator(Splitter splitterCharSequence toSplit) {
      this. = splitter.trimmer;
      this. = splitter.omitEmptyStrings;
      this. = splitter.limit;
      this. = toSplit;
    }
    @Override protected String computeNext() {
      /*
       * The returned string will be from the end of the last match to the
       * beginning of the next one. nextStart is the start position of the
       * returned substring, while offset is the place to start looking for a
       * separator.
       */
      int nextStart = ;
      while ( != -1) {
        int start = nextStart;
        int end;
        int separatorPosition = separatorStart();
        if (separatorPosition == -1) {
          end = .length();
           = -1;
        } else {
          end = separatorPosition;
           = separatorEnd(separatorPosition);
        }
        if ( == nextStart) {
          /*
           * This occurs when some pattern has an empty match, even if it
           * doesn't match the empty string -- for example, if it requires
           * lookahead or the like. The offset must be increased to look for
           * separators beyond this point, without changing the start position
           * of the next returned substring -- so nextStart stays the same.
           */
          ++;
          if ( >= .length()) {
             = -1;
          }
          continue;
        }
        while (start < end && .matches(.charAt(start))) {
          start++;
        }
        while (end > start && .matches(.charAt(end - 1))) {
          end--;
        }
        if ( && start == end) {
          // Don't include the (unused) separator in next split string.
          nextStart = ;
          continue;
        }
        if ( == 1) {
          // The limit has been reached, return the rest of the string as the
          // final item.  This is tested after empty string removal so that
          // empty strings do not count towards the limit.
          end = .length();
           = -1;
          // Since we may have changed the end, we need to trim it again.
          while (end > start && .matches(.charAt(end - 1))) {
            end--;
          }
        } else {
          --;
        }
        return .subSequence(startend).toString();
      }
      return endOfData();
    }
  }
New to GrepCode? Check out our FAQ X