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