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