001/*
002 * Copyright (C) 2009 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.base;
016
017import static com.google.common.base.Preconditions.checkArgument;
018import static com.google.common.base.Preconditions.checkNotNull;
019
020import com.google.common.annotations.GwtCompatible;
021import com.google.common.annotations.GwtIncompatible;
022import java.util.ArrayList;
023import java.util.Collections;
024import java.util.Iterator;
025import java.util.LinkedHashMap;
026import java.util.List;
027import java.util.Map;
028import java.util.regex.Pattern;
029import javax.annotation.CheckForNull;
030
031/**
032 * Extracts non-overlapping substrings from an input string, typically by recognizing appearances of
033 * a <i>separator</i> sequence. This separator can be specified as a single {@linkplain #on(char)
034 * character}, fixed {@linkplain #on(String) string}, {@linkplain #onPattern regular expression} or
035 * {@link #on(CharMatcher) CharMatcher} instance. Or, instead of using a separator at all, a
036 * splitter can extract adjacent substrings of a given {@linkplain #fixedLength fixed length}.
037 *
038 * <p>For example, this expression:
039 *
040 * <pre>{@code
041 * Splitter.on(',').split("foo,bar,qux")
042 * }</pre>
043 *
044 * ... produces an {@code Iterable} containing {@code "foo"}, {@code "bar"} and {@code "qux"}, in
045 * that order.
046 *
047 * <p>By default, {@code Splitter}'s behavior is simplistic and unassuming. The following
048 * expression:
049 *
050 * <pre>{@code
051 * Splitter.on(',').split(" foo,,,  bar ,")
052 * }</pre>
053 *
054 * ... yields the substrings {@code [" foo", "", "", " bar ", ""]}. If this is not the desired
055 * behavior, use configuration methods to obtain a <i>new</i> splitter instance with modified
056 * behavior:
057 *
058 * <pre>{@code
059 * private static final Splitter MY_SPLITTER = Splitter.on(',')
060 *     .trimResults()
061 *     .omitEmptyStrings();
062 * }</pre>
063 *
064 * <p>Now {@code MY_SPLITTER.split("foo,,, bar ,")} returns just {@code ["foo", "bar"]}. Note that
065 * the order in which these configuration methods are called is never significant.
066 *
067 * <p><b>Warning:</b> Splitter instances are immutable. Invoking a configuration method has no
068 * effect on the receiving instance; you must store and use the new splitter instance it returns
069 * instead.
070 *
071 * <pre>{@code
072 * // Do NOT do this
073 * Splitter splitter = Splitter.on('/');
074 * splitter.trimResults(); // does nothing!
075 * return splitter.split("wrong / wrong / wrong");
076 * }</pre>
077 *
078 * <p>For separator-based splitters that do not use {@code omitEmptyStrings}, an input string
079 * containing {@code n} occurrences of the separator naturally yields an iterable of size {@code n +
080 * 1}. So if the separator does not occur anywhere in the input, a single substring is returned
081 * containing the entire input. Consequently, all splitters split the empty string to {@code [""]}
082 * (note: even fixed-length splitters).
083 *
084 * <p>Splitter instances are thread-safe immutable, and are therefore safe to store as {@code static
085 * final} constants.
086 *
087 * <p>The {@link Joiner} class provides the inverse operation to splitting, but note that a
088 * round-trip between the two should be assumed to be lossy.
089 *
090 * <p>See the Guava User Guide article on <a
091 * href="https://github.com/google/guava/wiki/StringsExplained#splitter">{@code Splitter}</a>.
092 *
093 * @author Julien Silland
094 * @author Jesse Wilson
095 * @author Kevin Bourrillion
096 * @author Louis Wasserman
097 * @since 1.0
098 */
099@GwtCompatible(emulated = true)
100@ElementTypesAreNonnullByDefault
101public final class Splitter {
102  private final CharMatcher trimmer;
103  private final boolean omitEmptyStrings;
104  private final Strategy strategy;
105  private final int limit;
106
107  private Splitter(Strategy strategy) {
108    this(strategy, false, CharMatcher.none(), Integer.MAX_VALUE);
109  }
110
111  private Splitter(Strategy strategy, boolean omitEmptyStrings, CharMatcher trimmer, int limit) {
112    this.strategy = strategy;
113    this.omitEmptyStrings = omitEmptyStrings;
114    this.trimmer = trimmer;
115    this.limit = limit;
116  }
117
118  /**
119   * Returns a splitter that uses the given single-character separator. For example, {@code
120   * Splitter.on(',').split("foo,,bar")} returns an iterable containing {@code ["foo", "", "bar"]}.
121   *
122   * @param separator the character to recognize as a separator
123   * @return a splitter, with default settings, that recognizes that separator
124   */
125  public static Splitter on(char separator) {
126    return on(CharMatcher.is(separator));
127  }
128
129  /**
130   * Returns a splitter that considers any single character matched by the given {@code CharMatcher}
131   * to be a separator. For example, {@code
132   * Splitter.on(CharMatcher.anyOf(";,")).split("foo,;bar,quux")} returns an iterable containing
133   * {@code ["foo", "", "bar", "quux"]}.
134   *
135   * @param separatorMatcher a {@link CharMatcher} that determines whether a character is a
136   *     separator
137   * @return a splitter, with default settings, that uses this matcher
138   */
139  public static Splitter on(final CharMatcher separatorMatcher) {
140    checkNotNull(separatorMatcher);
141
142    return new Splitter(
143        new Strategy() {
144          @Override
145          public SplittingIterator iterator(Splitter splitter, final CharSequence toSplit) {
146            return new SplittingIterator(splitter, toSplit) {
147              @Override
148              int separatorStart(int start) {
149                return separatorMatcher.indexIn(toSplit, start);
150              }
151
152              @Override
153              int separatorEnd(int separatorPosition) {
154                return separatorPosition + 1;
155              }
156            };
157          }
158        });
159  }
160
161  /**
162   * Returns a splitter that uses the given fixed string as a separator. For example, {@code
163   * Splitter.on(", ").split("foo, bar,baz")} returns an iterable containing {@code ["foo",
164   * "bar,baz"]}.
165   *
166   * @param separator the literal, nonempty string to recognize as a separator
167   * @return a splitter, with default settings, that recognizes that separator
168   */
169  public static Splitter on(final String separator) {
170    checkArgument(separator.length() != 0, "The separator may not be the empty string.");
171    if (separator.length() == 1) {
172      return Splitter.on(separator.charAt(0));
173    }
174    return new Splitter(
175        new Strategy() {
176          @Override
177          public SplittingIterator iterator(Splitter splitter, CharSequence toSplit) {
178            return new SplittingIterator(splitter, toSplit) {
179              @Override
180              public int separatorStart(int start) {
181                int separatorLength = separator.length();
182
183                positions:
184                for (int p = start, last = toSplit.length() - separatorLength; p <= last; p++) {
185                  for (int i = 0; i < separatorLength; i++) {
186                    if (toSplit.charAt(i + p) != separator.charAt(i)) {
187                      continue positions;
188                    }
189                  }
190                  return p;
191                }
192                return -1;
193              }
194
195              @Override
196              public int separatorEnd(int separatorPosition) {
197                return separatorPosition + separator.length();
198              }
199            };
200          }
201        });
202  }
203
204  /**
205   * Returns a splitter that considers any subsequence matching {@code pattern} to be a separator.
206   * For example, {@code Splitter.on(Pattern.compile("\r?\n")).split(entireFile)} splits a string
207   * into lines whether it uses DOS-style or UNIX-style line terminators.
208   *
209   * @param separatorPattern the pattern that determines whether a subsequence is a separator. This
210   *     pattern may not match the empty string.
211   * @return a splitter, with default settings, that uses this pattern
212   * @throws IllegalArgumentException if {@code separatorPattern} matches the empty string
213   */
214  @GwtIncompatible // java.util.regex
215  public static Splitter on(Pattern separatorPattern) {
216    return onPatternInternal(new JdkPattern(separatorPattern));
217  }
218
219  /** Internal utility; see {@link #on(Pattern)} instead. */
220  static Splitter onPatternInternal(final CommonPattern separatorPattern) {
221    checkArgument(
222        !separatorPattern.matcher("").matches(),
223        "The pattern may not match the empty string: %s",
224        separatorPattern);
225
226    return new Splitter(
227        new Strategy() {
228          @Override
229          public SplittingIterator iterator(final Splitter splitter, CharSequence toSplit) {
230            final CommonMatcher matcher = separatorPattern.matcher(toSplit);
231            return new SplittingIterator(splitter, toSplit) {
232              @Override
233              public int separatorStart(int start) {
234                return matcher.find(start) ? matcher.start() : -1;
235              }
236
237              @Override
238              public int separatorEnd(int separatorPosition) {
239                return matcher.end();
240              }
241            };
242          }
243        });
244  }
245
246  /**
247   * Returns a splitter that considers any subsequence matching a given pattern (regular expression)
248   * to be a separator. For example, {@code Splitter.onPattern("\r?\n").split(entireFile)} splits a
249   * string into lines whether it uses DOS-style or UNIX-style line terminators. This is equivalent
250   * to {@code Splitter.on(Pattern.compile(pattern))}.
251   *
252   * @param separatorPattern the pattern that determines whether a subsequence is a separator. This
253   *     pattern may not match the empty string.
254   * @return a splitter, with default settings, that uses this pattern
255   * @throws IllegalArgumentException if {@code separatorPattern} matches the empty string or is a
256   *     malformed expression
257   */
258  @GwtIncompatible // java.util.regex
259  public static Splitter onPattern(String separatorPattern) {
260    return onPatternInternal(Platform.compilePattern(separatorPattern));
261  }
262
263  /**
264   * Returns a splitter that divides strings into pieces of the given length. For example, {@code
265   * Splitter.fixedLength(2).split("abcde")} returns an iterable containing {@code ["ab", "cd",
266   * "e"]}. The last piece can be smaller than {@code length} but will never be empty.
267   *
268   * <p><b>Note:</b> if {@link #fixedLength} is used in conjunction with {@link #limit}, the final
269   * split piece <i>may be longer than the specified fixed length</i>. This is because the splitter
270   * will <i>stop splitting when the limit is reached</i>, and just return the final piece as-is.
271   *
272   * <p><b>Exception:</b> for consistency with separator-based splitters, {@code split("")} does not
273   * yield an empty iterable, but an iterable containing {@code ""}. This is the only case in which
274   * {@code Iterables.size(split(input))} does not equal {@code IntMath.divide(input.length(),
275   * length, CEILING)}. To avoid this behavior, use {@code omitEmptyStrings}.
276   *
277   * @param length the desired length of pieces after splitting, a positive integer
278   * @return a splitter, with default settings, that can split into fixed sized pieces
279   * @throws IllegalArgumentException if {@code length} is zero or negative
280   */
281  public static Splitter fixedLength(final int length) {
282    checkArgument(length > 0, "The length may not be less than 1");
283
284    return new Splitter(
285        new Strategy() {
286          @Override
287          public SplittingIterator iterator(final Splitter splitter, CharSequence toSplit) {
288            return new SplittingIterator(splitter, toSplit) {
289              @Override
290              public int separatorStart(int start) {
291                int nextChunkStart = start + length;
292                return (nextChunkStart < toSplit.length() ? nextChunkStart : -1);
293              }
294
295              @Override
296              public int separatorEnd(int separatorPosition) {
297                return separatorPosition;
298              }
299            };
300          }
301        });
302  }
303
304  /**
305   * Returns a splitter that behaves equivalently to {@code this} splitter, but automatically omits
306   * empty strings from the results. For example, {@code
307   * Splitter.on(',').omitEmptyStrings().split(",a,,,b,c,,")} returns an iterable containing only
308   * {@code ["a", "b", "c"]}.
309   *
310   * <p>If either {@code trimResults} option is also specified when creating a splitter, that
311   * splitter always trims results first before checking for emptiness. So, for example, {@code
312   * Splitter.on(':').omitEmptyStrings().trimResults().split(": : : ")} returns an empty iterable.
313   *
314   * <p>Note that it is ordinarily not possible for {@link #split(CharSequence)} to return an empty
315   * iterable, but when using this option, it can (if the input sequence consists of nothing but
316   * separators).
317   *
318   * @return a splitter with the desired configuration
319   */
320  public Splitter omitEmptyStrings() {
321    return new Splitter(strategy, true, trimmer, limit);
322  }
323
324  /**
325   * Returns a splitter that behaves equivalently to {@code this} splitter but stops splitting after
326   * it reaches the limit. The limit defines the maximum number of items returned by the iterator,
327   * or the maximum size of the list returned by {@link #splitToList}.
328   *
329   * <p>For example, {@code Splitter.on(',').limit(3).split("a,b,c,d")} returns an iterable
330   * containing {@code ["a", "b", "c,d"]}. When omitting empty strings, the omitted strings do not
331   * count. Hence, {@code Splitter.on(',').limit(3).omitEmptyStrings().split("a,,,b,,,c,d")} returns
332   * an iterable containing {@code ["a", "b", "c,d"]}. When trim is requested, all entries are
333   * trimmed, including the last. Hence {@code Splitter.on(',').limit(3).trimResults().split(" a , b
334   * , c , d ")} results in {@code ["a", "b", "c , d"]}.
335   *
336   * @param maxItems the maximum number of items returned
337   * @return a splitter with the desired configuration
338   * @since 9.0
339   */
340  public Splitter limit(int maxItems) {
341    checkArgument(maxItems > 0, "must be greater than zero: %s", maxItems);
342    return new Splitter(strategy, omitEmptyStrings, trimmer, maxItems);
343  }
344
345  /**
346   * Returns a splitter that behaves equivalently to {@code this} splitter, but automatically
347   * removes leading and trailing {@linkplain CharMatcher#whitespace whitespace} from each returned
348   * substring; equivalent to {@code trimResults(CharMatcher.whitespace())}. For example, {@code
349   * Splitter.on(',').trimResults().split(" a, b ,c ")} returns an iterable containing {@code ["a",
350   * "b", "c"]}.
351   *
352   * @return a splitter with the desired configuration
353   */
354  public Splitter trimResults() {
355    return trimResults(CharMatcher.whitespace());
356  }
357
358  /**
359   * Returns a splitter that behaves equivalently to {@code this} splitter, but removes all leading
360   * or trailing characters matching the given {@code CharMatcher} from each returned substring. For
361   * example, {@code Splitter.on(',').trimResults(CharMatcher.is('_')).split("_a ,_b_ ,c__")}
362   * returns an iterable containing {@code ["a ", "b_ ", "c"]}.
363   *
364   * @param trimmer a {@link CharMatcher} that determines whether a character should be removed from
365   *     the beginning/end of a subsequence
366   * @return a splitter with the desired configuration
367   */
368  // TODO(kevinb): throw if a trimmer was already specified!
369  public Splitter trimResults(CharMatcher trimmer) {
370    checkNotNull(trimmer);
371    return new Splitter(strategy, omitEmptyStrings, trimmer, limit);
372  }
373
374  /**
375   * Splits {@code sequence} into string components and makes them available through an {@link
376   * Iterator}, which may be lazily evaluated. If you want an eagerly computed {@link List}, use
377   * {@link #splitToList(CharSequence)}.
378   *
379   * @param sequence the sequence of characters to split
380   * @return an iteration over the segments split from the parameter
381   */
382  public Iterable<String> split(final CharSequence sequence) {
383    checkNotNull(sequence);
384
385    return new Iterable<String>() {
386      @Override
387      public Iterator<String> iterator() {
388        return splittingIterator(sequence);
389      }
390
391      @Override
392      public String toString() {
393        return Joiner.on(", ")
394            .appendTo(new StringBuilder().append('['), this)
395            .append(']')
396            .toString();
397      }
398    };
399  }
400
401  private Iterator<String> splittingIterator(CharSequence sequence) {
402    return strategy.iterator(this, sequence);
403  }
404
405  /**
406   * Splits {@code sequence} into string components and returns them as an immutable list. If you
407   * want an {@link Iterable} which may be lazily evaluated, use {@link #split(CharSequence)}.
408   *
409   * @param sequence the sequence of characters to split
410   * @return an immutable list of the segments split from the parameter
411   * @since 15.0
412   */
413  public List<String> splitToList(CharSequence sequence) {
414    checkNotNull(sequence);
415
416    Iterator<String> iterator = splittingIterator(sequence);
417    List<String> result = new ArrayList<>();
418
419    while (iterator.hasNext()) {
420      result.add(iterator.next());
421    }
422
423    return Collections.unmodifiableList(result);
424  }
425
426  /**
427   * Returns a {@code MapSplitter} which splits entries based on this splitter, and splits entries
428   * into keys and values using the specified separator.
429   *
430   * @since 10.0
431   */
432  public MapSplitter withKeyValueSeparator(String separator) {
433    return withKeyValueSeparator(on(separator));
434  }
435
436  /**
437   * Returns a {@code MapSplitter} which splits entries based on this splitter, and splits entries
438   * into keys and values using the specified separator.
439   *
440   * @since 14.0
441   */
442  public MapSplitter withKeyValueSeparator(char separator) {
443    return withKeyValueSeparator(on(separator));
444  }
445
446  /**
447   * Returns a {@code MapSplitter} which splits entries based on this splitter, and splits entries
448   * into keys and values using the specified key-value splitter.
449   *
450   * <p>Note: Any configuration option configured on this splitter, such as {@link #trimResults},
451   * does not change the behavior of the {@code keyValueSplitter}.
452   *
453   * <p>Example:
454   *
455   * <pre>{@code
456   * String toSplit = " x -> y, z-> a ";
457   * Splitter outerSplitter = Splitter.on(',').trimResults();
458   * MapSplitter mapSplitter = outerSplitter.withKeyValueSeparator(Splitter.on("->"));
459   * Map<String, String> result = mapSplitter.split(toSplit);
460   * assertThat(result).isEqualTo(ImmutableMap.of("x ", " y", "z", " a"));
461   * }</pre>
462   *
463   * @since 10.0
464   */
465  public MapSplitter withKeyValueSeparator(Splitter keyValueSplitter) {
466    return new MapSplitter(this, keyValueSplitter);
467  }
468
469  /**
470   * An object that splits strings into maps as {@code Splitter} splits iterables and lists. Like
471   * {@code Splitter}, it is thread-safe and immutable. The common way to build instances is by
472   * providing an additional {@linkplain Splitter#withKeyValueSeparator key-value separator} to
473   * {@link Splitter}.
474   *
475   * @since 10.0
476   */
477  public static final class MapSplitter {
478    private static final String INVALID_ENTRY_MESSAGE = "Chunk [%s] is not a valid entry";
479    private final Splitter outerSplitter;
480    private final Splitter entrySplitter;
481
482    private MapSplitter(Splitter outerSplitter, Splitter entrySplitter) {
483      this.outerSplitter = outerSplitter; // only "this" is passed
484      this.entrySplitter = checkNotNull(entrySplitter);
485    }
486
487    /**
488     * Splits {@code sequence} into substrings, splits each substring into an entry, and returns an
489     * unmodifiable map with each of the entries. For example, {@code
490     * Splitter.on(';').trimResults().withKeyValueSeparator("=>").split("a=>b ; c=>b")} will return
491     * a mapping from {@code "a"} to {@code "b"} and {@code "c"} to {@code "b"}.
492     *
493     * <p>The returned map preserves the order of the entries from {@code sequence}.
494     *
495     * @throws IllegalArgumentException if the specified sequence does not split into valid map
496     *     entries, or if there are duplicate keys
497     */
498    public Map<String, String> split(CharSequence sequence) {
499      Map<String, String> map = new LinkedHashMap<>();
500      for (String entry : outerSplitter.split(sequence)) {
501        Iterator<String> entryFields = entrySplitter.splittingIterator(entry);
502
503        checkArgument(entryFields.hasNext(), INVALID_ENTRY_MESSAGE, entry);
504        String key = entryFields.next();
505        checkArgument(!map.containsKey(key), "Duplicate key [%s] found.", key);
506
507        checkArgument(entryFields.hasNext(), INVALID_ENTRY_MESSAGE, entry);
508        String value = entryFields.next();
509        map.put(key, value);
510
511        checkArgument(!entryFields.hasNext(), INVALID_ENTRY_MESSAGE, entry);
512      }
513      return Collections.unmodifiableMap(map);
514    }
515  }
516
517  private interface Strategy {
518    Iterator<String> iterator(Splitter splitter, CharSequence toSplit);
519  }
520
521  private abstract static class SplittingIterator extends AbstractIterator<String> {
522    final CharSequence toSplit;
523    final CharMatcher trimmer;
524    final boolean omitEmptyStrings;
525
526    /**
527     * Returns the first index in {@code toSplit} at or after {@code start} that contains the
528     * separator.
529     */
530    abstract int separatorStart(int start);
531
532    /**
533     * Returns the first index in {@code toSplit} after {@code separatorPosition} that does not
534     * contain a separator. This method is only invoked after a call to {@code separatorStart}.
535     */
536    abstract int separatorEnd(int separatorPosition);
537
538    int offset = 0;
539    int limit;
540
541    protected SplittingIterator(Splitter splitter, CharSequence toSplit) {
542      this.trimmer = splitter.trimmer;
543      this.omitEmptyStrings = splitter.omitEmptyStrings;
544      this.limit = splitter.limit;
545      this.toSplit = toSplit;
546    }
547
548    @CheckForNull
549    @Override
550    protected String computeNext() {
551      /*
552       * The returned string will be from the end of the last match to the beginning of the next
553       * one. nextStart is the start position of the returned substring, while offset is the place
554       * to start looking for a separator.
555       */
556      int nextStart = offset;
557      while (offset != -1) {
558        int start = nextStart;
559        int end;
560
561        int separatorPosition = separatorStart(offset);
562        if (separatorPosition == -1) {
563          end = toSplit.length();
564          offset = -1;
565        } else {
566          end = separatorPosition;
567          offset = separatorEnd(separatorPosition);
568        }
569        if (offset == nextStart) {
570          /*
571           * This occurs when some pattern has an empty match, even if it doesn't match the empty
572           * string -- for example, if it requires lookahead or the like. The offset must be
573           * increased to look for separators beyond this point, without changing the start position
574           * of the next returned substring -- so nextStart stays the same.
575           */
576          offset++;
577          if (offset > toSplit.length()) {
578            offset = -1;
579          }
580          continue;
581        }
582
583        while (start < end && trimmer.matches(toSplit.charAt(start))) {
584          start++;
585        }
586        while (end > start && trimmer.matches(toSplit.charAt(end - 1))) {
587          end--;
588        }
589
590        if (omitEmptyStrings && start == end) {
591          // Don't include the (unused) separator in next split string.
592          nextStart = offset;
593          continue;
594        }
595
596        if (limit == 1) {
597          // The limit has been reached, return the rest of the string as the
598          // final item. This is tested after empty string removal so that
599          // empty strings do not count towards the limit.
600          end = toSplit.length();
601          offset = -1;
602          // Since we may have changed the end, we need to trim it again.
603          while (end > start && trimmer.matches(toSplit.charAt(end - 1))) {
604            end--;
605          }
606        } else {
607          limit--;
608        }
609
610        return toSplit.subSequence(start, end).toString();
611      }
612      return endOfData();
613    }
614  }
615}