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