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