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