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