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