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>Note:</b> if {@link #fixedLength} is used in conjunction with {@link #limit}, the final
267   * split piece <i>may be longer than the specified fixed length</i>. This is because the splitter
268   * will <i>stop splitting when the limit is reached</i>, and just return the final piece as-is.
269   *
270   * <p><b>Exception:</b> for consistency with separator-based splitters, {@code split("")} does not
271   * yield an empty iterable, but an iterable containing {@code ""}. This is the only case in which
272   * {@code Iterables.size(split(input))} does not equal {@code IntMath.divide(input.length(),
273   * length, CEILING)}. To avoid this behavior, use {@code omitEmptyStrings}.
274   *
275   * @param length the desired length of pieces after splitting, a positive integer
276   * @return a splitter, with default settings, that can split into fixed sized pieces
277   * @throws IllegalArgumentException if {@code length} is zero or negative
278   */
279  public static Splitter fixedLength(final int length) {
280    checkArgument(length > 0, "The length may not be less than 1");
281
282    return new Splitter(
283        new Strategy() {
284          @Override
285          public SplittingIterator iterator(final Splitter splitter, CharSequence toSplit) {
286            return new SplittingIterator(splitter, toSplit) {
287              @Override
288              public int separatorStart(int start) {
289                int nextChunkStart = start + length;
290                return (nextChunkStart < toSplit.length() ? nextChunkStart : -1);
291              }
292
293              @Override
294              public int separatorEnd(int separatorPosition) {
295                return separatorPosition;
296              }
297            };
298          }
299        });
300  }
301
302  /**
303   * Returns a splitter that behaves equivalently to {@code this} splitter, but automatically omits
304   * empty strings from the results. For example, {@code
305   * Splitter.on(',').omitEmptyStrings().split(",a,,,b,c,,")} returns an iterable containing only
306   * {@code ["a", "b", "c"]}.
307   *
308   * <p>If either {@code trimResults} option is also specified when creating a splitter, that
309   * splitter always trims results first before checking for emptiness. So, for example, {@code
310   * Splitter.on(':').omitEmptyStrings().trimResults().split(": : : ")} returns an empty iterable.
311   *
312   * <p>Note that it is ordinarily not possible for {@link #split(CharSequence)} to return an empty
313   * iterable, but when using this option, it can (if the input sequence consists of nothing but
314   * separators).
315   *
316   * @return a splitter with the desired configuration
317   */
318  public Splitter omitEmptyStrings() {
319    return new Splitter(strategy, true, trimmer, limit);
320  }
321
322  /**
323   * Returns a splitter that behaves equivalently to {@code this} splitter but stops splitting after
324   * it reaches the limit. The limit defines the maximum number of items returned by the iterator,
325   * or the maximum size of the list returned by {@link #splitToList}.
326   *
327   * <p>For example, {@code Splitter.on(',').limit(3).split("a,b,c,d")} returns an iterable
328   * containing {@code ["a", "b", "c,d"]}. When omitting empty strings, the omitted strings do not
329   * count. Hence, {@code Splitter.on(',').limit(3).omitEmptyStrings().split("a,,,b,,,c,d")} returns
330   * an iterable containing {@code ["a", "b", "c,d"}. When trim is requested, all entries are
331   * trimmed, including the last. Hence {@code Splitter.on(',').limit(3).trimResults().split(" a , b
332   * , c , d ")} results in {@code ["a", "b", "c , d"]}.
333   *
334   * @param limit the maximum number of items returned
335   * @return a splitter with the desired configuration
336   * @since 9.0
337   */
338  public Splitter limit(int limit) {
339    checkArgument(limit > 0, "must be greater than zero: %s", limit);
340    return new Splitter(strategy, omitEmptyStrings, trimmer, limit);
341  }
342
343  /**
344   * Returns a splitter that behaves equivalently to {@code this} splitter, but automatically
345   * removes leading and trailing {@linkplain CharMatcher#whitespace whitespace} from each returned
346   * substring; equivalent to {@code trimResults(CharMatcher.whitespace())}. For example, {@code
347   * Splitter.on(',').trimResults().split(" a, b ,c ")} returns an iterable containing {@code ["a",
348   * "b", "c"]}.
349   *
350   * @return a splitter with the desired configuration
351   */
352  public Splitter trimResults() {
353    return trimResults(CharMatcher.whitespace());
354  }
355
356  /**
357   * Returns a splitter that behaves equivalently to {@code this} splitter, but removes all leading
358   * or trailing characters matching the given {@code CharMatcher} from each returned substring. For
359   * example, {@code Splitter.on(',').trimResults(CharMatcher.is('_')).split("_a ,_b_ ,c__")}
360   * returns an iterable containing {@code ["a ", "b_ ", "c"]}.
361   *
362   * @param trimmer a {@link CharMatcher} that determines whether a character should be removed from
363   *     the beginning/end of a subsequence
364   * @return a splitter with the desired configuration
365   */
366  // TODO(kevinb): throw if a trimmer was already specified!
367  public Splitter trimResults(CharMatcher trimmer) {
368    checkNotNull(trimmer);
369    return new Splitter(strategy, omitEmptyStrings, trimmer, limit);
370  }
371
372  /**
373   * Splits {@code sequence} into string components and makes them available through an {@link
374   * Iterator}, which may be lazily evaluated. If you want an eagerly computed {@link List}, use
375   * {@link #splitToList(CharSequence)}.
376   *
377   * @param sequence the sequence of characters to split
378   * @return an iteration over the segments split from the parameter
379   */
380  public Iterable<String> split(final CharSequence sequence) {
381    checkNotNull(sequence);
382
383    return new Iterable<String>() {
384      @Override
385      public Iterator<String> iterator() {
386        return splittingIterator(sequence);
387      }
388
389      @Override
390      public String toString() {
391        return Joiner.on(", ")
392            .appendTo(new StringBuilder().append('['), this)
393            .append(']')
394            .toString();
395      }
396    };
397  }
398
399  private Iterator<String> splittingIterator(CharSequence sequence) {
400    return strategy.iterator(this, sequence);
401  }
402
403  /**
404   * Splits {@code sequence} into string components and returns them as an immutable list. If you
405   * want an {@link Iterable} which may be lazily evaluated, use {@link #split(CharSequence)}.
406   *
407   * @param sequence the sequence of characters to split
408   * @return an immutable list of the segments split from the parameter
409   * @since 15.0
410   */
411  public List<String> splitToList(CharSequence sequence) {
412    checkNotNull(sequence);
413
414    Iterator<String> iterator = splittingIterator(sequence);
415    List<String> result = new ArrayList<>();
416
417    while (iterator.hasNext()) {
418      result.add(iterator.next());
419    }
420
421    return Collections.unmodifiableList(result);
422  }
423
424  /**
425   * Returns a {@code MapSplitter} which splits entries based on this splitter, and splits entries
426   * into keys and values using the specified separator.
427   *
428   * @since 10.0
429   */
430  @Beta
431  public MapSplitter withKeyValueSeparator(String separator) {
432    return withKeyValueSeparator(on(separator));
433  }
434
435  /**
436   * Returns a {@code MapSplitter} which splits entries based on this splitter, and splits entries
437   * into keys and values using the specified separator.
438   *
439   * @since 14.0
440   */
441  @Beta
442  public MapSplitter withKeyValueSeparator(char separator) {
443    return withKeyValueSeparator(on(separator));
444  }
445
446  /**
447   * Returns a {@code MapSplitter} which splits entries based on this splitter, and splits entries
448   * into keys and values using the specified key-value splitter.
449   *
450   * <p>Note: Any configuration option configured on this splitter, such as {@link #trimResults},
451   * does not change the behavior of the {@code keyValueSplitter}.
452   *
453   * <p>Example:
454   *
455   * <pre>{@code
456   * String toSplit = " x -> y, z-> a ";
457   * Splitter outerSplitter = Splitter.on(',').trimResults();
458   * MapSplitter mapSplitter = outerSplitter.withKeyValueSeparator(Splitter.on("->"));
459   * Map<String, String> result = mapSplitter.split(toSplit);
460   * assertThat(result).isEqualTo(ImmutableMap.of("x ", " y", "z", " a"));
461   * }</pre>
462   *
463   * @since 10.0
464   */
465  @Beta
466  public MapSplitter withKeyValueSeparator(Splitter keyValueSplitter) {
467    return new MapSplitter(this, keyValueSplitter);
468  }
469
470  /**
471   * An object that splits strings into maps as {@code Splitter} splits iterables and lists. Like
472   * {@code Splitter}, it is thread-safe and immutable. The common way to build instances is by
473   * providing an additional {@linkplain Splitter#withKeyValueSeparator key-value separator} to
474   * {@link Splitter}.
475   *
476   * @since 10.0
477   */
478  @Beta
479  public static final class MapSplitter {
480    private static final String INVALID_ENTRY_MESSAGE = "Chunk [%s] is not a valid entry";
481    private final Splitter outerSplitter;
482    private final Splitter entrySplitter;
483
484    private MapSplitter(Splitter outerSplitter, Splitter entrySplitter) {
485      this.outerSplitter = outerSplitter; // only "this" is passed
486      this.entrySplitter = checkNotNull(entrySplitter);
487    }
488
489    /**
490     * Splits {@code sequence} into substrings, splits each substring into an entry, and returns an
491     * unmodifiable map with each of the entries. For example, {@code
492     * Splitter.on(';').trimResults().withKeyValueSeparator("=>").split("a=>b ; c=>b")} will return
493     * a mapping from {@code "a"} to {@code "b"} and {@code "c"} to {@code "b"}.
494     *
495     * <p>The returned map preserves the order of the entries from {@code sequence}.
496     *
497     * @throws IllegalArgumentException if the specified sequence does not split into valid map
498     *     entries, or if there are duplicate keys
499     */
500    public Map<String, String> split(CharSequence sequence) {
501      Map<String, String> map = new LinkedHashMap<>();
502      for (String entry : outerSplitter.split(sequence)) {
503        Iterator<String> entryFields = entrySplitter.splittingIterator(entry);
504
505        checkArgument(entryFields.hasNext(), INVALID_ENTRY_MESSAGE, entry);
506        String key = entryFields.next();
507        checkArgument(!map.containsKey(key), "Duplicate key [%s] found.", key);
508
509        checkArgument(entryFields.hasNext(), INVALID_ENTRY_MESSAGE, entry);
510        String value = entryFields.next();
511        map.put(key, value);
512
513        checkArgument(!entryFields.hasNext(), INVALID_ENTRY_MESSAGE, entry);
514      }
515      return Collections.unmodifiableMap(map);
516    }
517  }
518
519  private interface Strategy {
520    Iterator<String> iterator(Splitter splitter, CharSequence toSplit);
521  }
522
523  private abstract static class SplittingIterator extends AbstractIterator<String> {
524    final CharSequence toSplit;
525    final CharMatcher trimmer;
526    final boolean omitEmptyStrings;
527
528    /**
529     * Returns the first index in {@code toSplit} at or after {@code start} that contains the
530     * separator.
531     */
532    abstract int separatorStart(int start);
533
534    /**
535     * Returns the first index in {@code toSplit} after {@code separatorPosition} that does not
536     * contain a separator. This method is only invoked after a call to {@code separatorStart}.
537     */
538    abstract int separatorEnd(int separatorPosition);
539
540    int offset = 0;
541    int limit;
542
543    protected SplittingIterator(Splitter splitter, CharSequence toSplit) {
544      this.trimmer = splitter.trimmer;
545      this.omitEmptyStrings = splitter.omitEmptyStrings;
546      this.limit = splitter.limit;
547      this.toSplit = toSplit;
548    }
549
550    @Override
551    protected String computeNext() {
552      /*
553       * The returned string will be from the end of the last match to the beginning of the next
554       * one. nextStart is the start position of the returned substring, while offset is the place
555       * to start looking for a separator.
556       */
557      int nextStart = offset;
558      while (offset != -1) {
559        int start = nextStart;
560        int end;
561
562        int separatorPosition = separatorStart(offset);
563        if (separatorPosition == -1) {
564          end = toSplit.length();
565          offset = -1;
566        } else {
567          end = separatorPosition;
568          offset = separatorEnd(separatorPosition);
569        }
570        if (offset == nextStart) {
571          /*
572           * This occurs when some pattern has an empty match, even if it doesn't match the empty
573           * string -- for example, if it requires lookahead or the like. The offset must be
574           * increased to look for separators beyond this point, without changing the start position
575           * of the next returned substring -- so nextStart stays the same.
576           */
577          offset++;
578          if (offset > toSplit.length()) {
579            offset = -1;
580          }
581          continue;
582        }
583
584        while (start < end && trimmer.matches(toSplit.charAt(start))) {
585          start++;
586        }
587        while (end > start && trimmer.matches(toSplit.charAt(end - 1))) {
588          end--;
589        }
590
591        if (omitEmptyStrings && start == end) {
592          // Don't include the (unused) separator in next split string.
593          nextStart = offset;
594          continue;
595        }
596
597        if (limit == 1) {
598          // The limit has been reached, return the rest of the string as the
599          // final item. This is tested after empty string removal so that
600          // empty strings do not count towards the limit.
601          end = toSplit.length();
602          offset = -1;
603          // Since we may have changed the end, we need to trim it again.
604          while (end > start && trimmer.matches(toSplit.charAt(end - 1))) {
605            end--;
606          }
607        } else {
608          limit--;
609        }
610
611        return toSplit.subSequence(start, end).toString();
612      }
613      return endOfData();
614    }
615  }
616}