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
017 package com.google.common.base;
018
019 import static com.google.common.base.Preconditions.checkArgument;
020 import static com.google.common.base.Preconditions.checkNotNull;
021
022 import com.google.common.annotations.Beta;
023 import com.google.common.annotations.GwtCompatible;
024 import com.google.common.annotations.GwtIncompatible;
025
026 import java.util.Collections;
027 import java.util.Iterator;
028 import java.util.LinkedHashMap;
029 import java.util.Map;
030 import java.util.regex.Matcher;
031 import java.util.regex.Pattern;
032
033 import javax.annotation.CheckReturnValue;
034
035 /**
036 * An object that divides strings (or other instances of {@code CharSequence})
037 * into substrings, by recognizing a <i>separator</i> (a.k.a. "delimiter")
038 * which can be expressed as a single character, literal string, regular
039 * expression, {@code CharMatcher}, or by using a fixed substring length. This
040 * class provides the complementary functionality to {@link Joiner}.
041 *
042 * <p>Here is the most basic example of {@code Splitter} usage: <pre> {@code
043 *
044 * Splitter.on(',').split("foo,bar")}</pre>
045 *
046 * This invocation returns an {@code Iterable<String>} containing {@code "foo"}
047 * and {@code "bar"}, in that order.
048 *
049 * <p>By default {@code Splitter}'s behavior is very simplistic: <pre> {@code
050 *
051 * Splitter.on(',').split("foo,,bar, quux")}</pre>
052 *
053 * This returns an iterable containing {@code ["foo", "", "bar", " quux"]}.
054 * Notice that the splitter does not assume that you want empty strings removed,
055 * or that you wish to trim whitespace. If you want features like these, simply
056 * ask for them: <pre> {@code
057 *
058 * private static final Splitter MY_SPLITTER = Splitter.on(',')
059 * .trimResults()
060 * .omitEmptyStrings();}</pre>
061 *
062 * Now {@code MY_SPLITTER.split("foo, ,bar, quux,")} returns an iterable
063 * containing just {@code ["foo", "bar", "quux"]}. Note that the order in which
064 * the configuration methods are called is never significant; for instance,
065 * trimming is always applied first before checking for an empty result,
066 * regardless of the order in which the {@link #trimResults()} and
067 * {@link #omitEmptyStrings()} methods were invoked.
068 *
069 * <p><b>Warning: splitter instances are always immutable</b>; a configuration
070 * method such as {@code omitEmptyStrings} has no effect on the instance it
071 * is invoked on! You must store and use the new splitter instance returned by
072 * the method. This makes splitters thread-safe, and safe to store as {@code
073 * static final} constants (as illustrated above). <pre> {@code
074 *
075 * // Bad! Do not do this!
076 * Splitter splitter = Splitter.on('/');
077 * splitter.trimResults(); // does nothing!
078 * return splitter.split("wrong / wrong / wrong");}</pre>
079 *
080 * The separator recognized by the splitter does not have to be a single
081 * literal character as in the examples above. See the methods {@link
082 * #on(String)}, {@link #on(Pattern)} and {@link #on(CharMatcher)} for examples
083 * of other ways to specify separators.
084 *
085 * <p><b>Note:</b> this class does not mimic any of the quirky behaviors of
086 * similar JDK methods; for instance, it does not silently discard trailing
087 * separators, as does {@link String#split(String)}, nor does it have a default
088 * behavior of using five particular whitespace characters as separators, like
089 * {@link java.util.StringTokenizer}.
090 *
091 * <p>See the Guava User Guide article on <a href=
092 * "http://code.google.com/p/guava-libraries/wiki/StringsExplained#Splitter">
093 * {@code Splitter}</a>.
094 *
095 * @author Julien Silland
096 * @author Jesse Wilson
097 * @author Kevin Bourrillion
098 * @author Louis Wasserman
099 * @since 1.0
100 */
101 @GwtCompatible(emulated = true)
102 public final class Splitter {
103 private final CharMatcher trimmer;
104 private final boolean omitEmptyStrings;
105 private final Strategy strategy;
106 private final int limit;
107
108 private Splitter(Strategy strategy) {
109 this(strategy, false, CharMatcher.NONE, Integer.MAX_VALUE);
110 }
111
112 private Splitter(Strategy strategy, boolean omitEmptyStrings,
113 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 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
134 * given {@code CharMatcher} to be a separator. For example, {@code
135 * Splitter.on(CharMatcher.anyOf(";,")).split("foo,;bar,quux")} returns an
136 * iterable containing {@code ["foo", "", "bar", "quux"]}.
137 *
138 * @param separatorMatcher a {@link CharMatcher} that determines whether a
139 * character is a 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(new Strategy() {
146 public SplittingIterator iterator(
147 Splitter splitter, final CharSequence toSplit) {
148 return new SplittingIterator(splitter, toSplit) {
149
150 @Override
151 int separatorStart(int start) {
152 return separatorMatcher.indexIn(toSplit, start);
153 }
154
155
156 @Override
157 int separatorEnd(int separatorPosition) {
158 return separatorPosition + 1;
159 }
160 };
161 }
162 });
163 }
164
165 /**
166 * Returns a splitter that uses the given fixed string as a separator. For
167 * example, {@code Splitter.on(", ").split("foo, bar, baz,qux")} returns an
168 * iterable containing {@code ["foo", "bar", "baz,qux"]}.
169 *
170 * @param separator the literal, nonempty string to recognize as a separator
171 * @return a splitter, with default settings, that recognizes that separator
172 */
173 public static Splitter on(final String separator) {
174 checkArgument(separator.length() != 0,
175 "The separator may not be the empty string.");
176
177 return new Splitter(new Strategy() {
178 public SplittingIterator iterator(
179 Splitter splitter, CharSequence toSplit) {
180 return new SplittingIterator(splitter, toSplit) {
181
182 @Override
183 public int separatorStart(int start) {
184 int delimeterLength = separator.length();
185
186 positions:
187 for (int p = start, last = toSplit.length() - delimeterLength;
188 p <= last; p++) {
189 for (int i = 0; i < delimeterLength; 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
200 @Override
201 public int separatorEnd(int separatorPosition) {
202 return separatorPosition + separator.length();
203 }
204 };
205 }
206 });
207 }
208
209 /**
210 * Returns a splitter that considers any subsequence matching {@code
211 * pattern} to be a separator. For example, {@code
212 * Splitter.on(Pattern.compile("\r?\n")).split(entireFile)} splits a string
213 * into lines whether it uses DOS-style or UNIX-style line terminators.
214 *
215 * @param separatorPattern the pattern that determines whether a subsequence
216 * is a separator. This pattern may not match the empty string.
217 * @return a splitter, with default settings, that uses this pattern
218 * @throws IllegalArgumentException if {@code separatorPattern} matches the
219 * empty string
220 */
221 @GwtIncompatible("java.util.regex")
222 public static Splitter on(final Pattern separatorPattern) {
223 checkNotNull(separatorPattern);
224 checkArgument(!separatorPattern.matcher("").matches(),
225 "The pattern may not match the empty string: %s", separatorPattern);
226
227 return new Splitter(new Strategy() {
228 public SplittingIterator iterator(
229 final Splitter splitter, CharSequence toSplit) {
230 final Matcher matcher = separatorPattern.matcher(toSplit);
231 return new SplittingIterator(splitter, toSplit) {
232
233 @Override
234 public int separatorStart(int start) {
235 return matcher.find(start) ? matcher.start() : -1;
236 }
237
238
239 @Override
240 public int separatorEnd(int separatorPosition) {
241 return matcher.end();
242 }
243 };
244 }
245 });
246 }
247
248 /**
249 * Returns a splitter that considers any subsequence matching a given
250 * pattern (regular expression) to be a separator. For example, {@code
251 * Splitter.onPattern("\r?\n").split(entireFile)} splits a string into lines
252 * whether it uses DOS-style or UNIX-style line terminators. This is
253 * equivalent to {@code Splitter.on(Pattern.compile(pattern))}.
254 *
255 * @param separatorPattern the pattern that determines whether a subsequence
256 * is a separator. This pattern may not match the empty string.
257 * @return a splitter, with default settings, that uses this pattern
258 * @throws java.util.regex.PatternSyntaxException if {@code separatorPattern}
259 * is a malformed expression
260 * @throws IllegalArgumentException if {@code separatorPattern} matches the
261 * empty string
262 */
263 @GwtIncompatible("java.util.regex")
264 public static Splitter onPattern(String separatorPattern) {
265 return on(Pattern.compile(separatorPattern));
266 }
267
268 /**
269 * Returns a splitter that divides strings into pieces of the given length.
270 * For example, {@code Splitter.fixedLength(2).split("abcde")} returns an
271 * iterable containing {@code ["ab", "cd", "e"]}. The last piece can be
272 * smaller than {@code length} but will never be empty.
273 *
274 * @param length the desired length of pieces after splitting
275 * @return a splitter, with default settings, that can split into fixed sized
276 * pieces
277 */
278 public static Splitter fixedLength(final int length) {
279 checkArgument(length > 0, "The length may not be less than 1");
280
281 return new Splitter(new Strategy() {
282 public SplittingIterator iterator(
283 final Splitter splitter, CharSequence toSplit) {
284 return new SplittingIterator(splitter, toSplit) {
285
286 @Override
287 public int separatorStart(int start) {
288 int nextChunkStart = start + length;
289 return (nextChunkStart < toSplit.length() ? nextChunkStart : -1);
290 }
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
304 * automatically omits empty strings from the results. For example, {@code
305 * Splitter.on(',').omitEmptyStrings().split(",a,,,b,c,,")} returns an
306 * iterable containing only {@code ["a", "b", "c"]}.
307 *
308 * <p>If either {@code trimResults} option is also specified when creating a
309 * splitter, that splitter always trims results first before checking for
310 * emptiness. So, for example, {@code
311 * Splitter.on(':').omitEmptyStrings().trimResults().split(": : : ")} returns
312 * an empty iterable.
313 *
314 * <p>Note that it is ordinarily not possible for {@link #split(CharSequence)}
315 * to return an empty iterable, but when using this option, it can (if the
316 * input sequence consists of nothing but separators).
317 *
318 * @return a splitter with the desired configuration
319 */
320 @CheckReturnValue
321 public Splitter omitEmptyStrings() {
322 return new Splitter(strategy, true, trimmer, limit);
323 }
324
325 /**
326 * Returns a splitter that behaves equivalently to {@code this} splitter but
327 * stops splitting after it reaches the limit.
328 * The limit defines the maximum number of items returned by the iterator.
329 *
330 * <p>For example,
331 * {@code Splitter.on(',').limit(3).split("a,b,c,d")} returns an iterable
332 * containing {@code ["a", "b", "c,d"]}. When omitting empty strings, the
333 * omitted strings do no count. Hence,
334 * {@code Splitter.on(',').limit(3).omitEmptyStrings().split("a,,,b,,,c,d")}
335 * returns an iterable containing {@code ["a", "b", "c,d"}.
336 * When trim is requested, all entries, including the last are trimmed. Hence
337 * {@code Splitter.on(',').limit(3).trimResults().split(" a , b , c , d ")}
338 * results in @{code ["a", "b", "c , d"]}.
339 *
340 * @param limit the maximum number of items returns
341 * @return a splitter with the desired configuration
342 * @since 9.0
343 */
344 @CheckReturnValue
345 public Splitter limit(int limit) {
346 checkArgument(limit > 0, "must be greater than zero: %s", limit);
347 return new Splitter(strategy, omitEmptyStrings, trimmer, limit);
348 }
349
350 /**
351 * Returns a splitter that behaves equivalently to {@code this} splitter, but
352 * automatically removes leading and trailing {@linkplain
353 * CharMatcher#WHITESPACE whitespace} from each returned substring; equivalent
354 * to {@code trimResults(CharMatcher.WHITESPACE)}. For example, {@code
355 * Splitter.on(',').trimResults().split(" a, b ,c ")} returns an iterable
356 * containing {@code ["a", "b", "c"]}.
357 *
358 * @return a splitter with the desired configuration
359 */
360 @CheckReturnValue
361 public Splitter trimResults() {
362 return trimResults(CharMatcher.WHITESPACE);
363 }
364
365 /**
366 * Returns a splitter that behaves equivalently to {@code this} splitter, but
367 * removes all leading or trailing characters matching the given {@code
368 * CharMatcher} from each returned substring. For example, {@code
369 * Splitter.on(',').trimResults(CharMatcher.is('_')).split("_a ,_b_ ,c__")}
370 * returns an iterable containing {@code ["a ", "b_ ", "c"]}.
371 *
372 * @param trimmer a {@link CharMatcher} that determines whether a character
373 * should be removed from the beginning/end of a subsequence
374 * @return a splitter with the desired configuration
375 */
376 // TODO(kevinb): throw if a trimmer was already specified!
377 @CheckReturnValue
378 public Splitter trimResults(CharMatcher trimmer) {
379 checkNotNull(trimmer);
380 return new Splitter(strategy, omitEmptyStrings, trimmer, limit);
381 }
382
383 /**
384 * Splits {@code sequence} into string components and makes them available
385 * through an {@link Iterator}, which may be lazily evaluated.
386 *
387 * @param sequence the sequence of characters to split
388 * @return an iteration over the segments split from the parameter.
389 */
390 public Iterable<String> split(final CharSequence sequence) {
391 checkNotNull(sequence);
392
393 return new Iterable<String>() {
394 public Iterator<String> iterator() {
395 return spliterator(sequence);
396 }
397 @Override
398 public String toString() {
399 return Joiner.on(", ")
400 .appendTo(new StringBuilder().append('['), this)
401 .append(']')
402 .toString();
403 }
404 };
405 }
406
407 private Iterator<String> spliterator(CharSequence sequence) {
408 return strategy.iterator(this, sequence);
409 }
410
411 /**
412 * Returns a {@code MapSplitter} which splits entries based on this splitter,
413 * and splits entries into keys and values using the specified separator.
414 *
415 * @since 10.0
416 */
417 @CheckReturnValue
418 @Beta
419 public MapSplitter withKeyValueSeparator(String separator) {
420 return withKeyValueSeparator(on(separator));
421 }
422
423 /**
424 * Returns a {@code MapSplitter} which splits entries based on this splitter,
425 * and splits entries into keys and values using the specified key-value
426 * splitter.
427 *
428 * @since 10.0
429 */
430 @CheckReturnValue
431 @Beta
432 public MapSplitter withKeyValueSeparator(Splitter keyValueSplitter) {
433 return new MapSplitter(this, keyValueSplitter);
434 }
435
436 /**
437 * An object that splits strings into maps as {@code Splitter} splits
438 * iterables and lists. Like {@code Splitter}, it is thread-safe and
439 * immutable.
440 *
441 * @since 10.0
442 */
443 @Beta
444 public static final class MapSplitter {
445 private static final String INVALID_ENTRY_MESSAGE =
446 "Chunk [%s] is not a valid entry";
447 private final Splitter outerSplitter;
448 private final Splitter entrySplitter;
449
450 private MapSplitter(Splitter outerSplitter, Splitter entrySplitter) {
451 this.outerSplitter = outerSplitter; // only "this" is passed
452 this.entrySplitter = checkNotNull(entrySplitter);
453 }
454
455 /**
456 * Splits {@code sequence} into substrings, splits each substring into
457 * an entry, and returns an unmodifiable map with each of the entries. For
458 * example, <code>
459 * Splitter.on(';').trimResults().withKeyValueSeparator("=>")
460 * .split("a=>b ; c=>b")
461 * </code> will return a mapping from {@code "a"} to {@code "b"} and
462 * {@code "c"} to {@code b}.
463 *
464 * <p>The returned map preserves the order of the entries from
465 * {@code sequence}.
466 *
467 * @throws IllegalArgumentException if the specified sequence does not split
468 * into valid map entries, or if there are duplicate keys
469 */
470 public Map<String, String> split(CharSequence sequence) {
471 Map<String, String> map = new LinkedHashMap<String, String>();
472 for (String entry : outerSplitter.split(sequence)) {
473 Iterator<String> entryFields = entrySplitter.spliterator(entry);
474
475 checkArgument(entryFields.hasNext(), INVALID_ENTRY_MESSAGE, entry);
476 String key = entryFields.next();
477 checkArgument(!map.containsKey(key), "Duplicate key [%s] found.", key);
478
479 checkArgument(entryFields.hasNext(), INVALID_ENTRY_MESSAGE, entry);
480 String value = entryFields.next();
481 map.put(key, value);
482
483 checkArgument(!entryFields.hasNext(), INVALID_ENTRY_MESSAGE, entry);
484 }
485 return Collections.unmodifiableMap(map);
486 }
487 }
488
489 private interface Strategy {
490 Iterator<String> iterator(Splitter splitter, CharSequence toSplit);
491 }
492
493 private abstract static class SplittingIterator extends AbstractIterator<String> {
494 final CharSequence toSplit;
495 final CharMatcher trimmer;
496 final boolean omitEmptyStrings;
497
498 /**
499 * Returns the first index in {@code toSplit} at or after {@code start}
500 * that contains the separator.
501 */
502 abstract int separatorStart(int start);
503
504 /**
505 * Returns the first index in {@code toSplit} after {@code
506 * separatorPosition} that does not contain a separator. This method is only
507 * invoked after a call to {@code separatorStart}.
508 */
509 abstract int separatorEnd(int separatorPosition);
510
511 int offset = 0;
512 int limit;
513
514 protected SplittingIterator(Splitter splitter, CharSequence toSplit) {
515 this.trimmer = splitter.trimmer;
516 this.omitEmptyStrings = splitter.omitEmptyStrings;
517 this.limit = splitter.limit;
518 this.toSplit = toSplit;
519 }
520
521
522 @Override
523 protected String computeNext() {
524 /*
525 * The returned string will be from the end of the last match to the
526 * beginning of the next one. nextStart is the start position of the
527 * returned substring, while offset is the place to start looking for a
528 * separator.
529 */
530 int nextStart = offset;
531 while (offset != -1) {
532 int start = nextStart;
533 int end;
534
535 int separatorPosition = separatorStart(offset);
536 if (separatorPosition == -1) {
537 end = toSplit.length();
538 offset = -1;
539 } else {
540 end = separatorPosition;
541 offset = separatorEnd(separatorPosition);
542 }
543 if (offset == nextStart) {
544 /*
545 * This occurs when some pattern has an empty match, even if it
546 * doesn't match the empty string -- for example, if it requires
547 * lookahead or the like. The offset must be increased to look for
548 * separators beyond this point, without changing the start position
549 * of the next returned substring -- so nextStart stays the same.
550 */
551 offset++;
552 if (offset >= toSplit.length()) {
553 offset = -1;
554 }
555 continue;
556 }
557
558 while (start < end && trimmer.matches(toSplit.charAt(start))) {
559 start++;
560 }
561 while (end > start && trimmer.matches(toSplit.charAt(end - 1))) {
562 end--;
563 }
564
565 if (omitEmptyStrings && start == end) {
566 // Don't include the (unused) separator in next split string.
567 nextStart = offset;
568 continue;
569 }
570
571 if (limit == 1) {
572 // The limit has been reached, return the rest of the string as the
573 // final item. This is tested after empty string removal so that
574 // empty strings do not count towards the limit.
575 end = toSplit.length();
576 offset = -1;
577 // Since we may have changed the end, we need to trim it again.
578 while (end > start && trimmer.matches(toSplit.charAt(end - 1))) {
579 end--;
580 }
581 } else {
582 limit--;
583 }
584
585 return toSplit.subSequence(start, end).toString();
586 }
587 return endOfData();
588 }
589 }
590 }