Splitter.onAny(String...)
See original GitHub issueSometimes, I’d like to split either on ';'
or ','
. For that, I can use a CharMatcher.ofAny(",;")
.
But it also happens that I want to split on "; "
or ", "
with spaces. Well, maybe those are parameters. So let’s just say I don’t know them at compile-time.
Good, I could write a regex. So let’s write it:
String[] separators = { "; ", ", " };
String splitterPattern = String.format("(?:%s|%s)", Pattern.quote(separators[0]), Pattern.quote(separators[1]));
Hmm… That’s verbose. And I have only two separators. Let’s make it generic for more :
String[] separators = { "; ", ", ", ". " };
String splitterPattern = "(?:" + FluentIterable.from(separators).transform(Pattern::quote).join("|") + ")";
Well, now that’s rational (yeah, I used FluentIterable
and not a Stream
because the Guava’s join
is much, much better), but it’s not instinctive. It took me a good 30 minutes to get to something that small, pondering which of Stream
or FluentIterable
to use, and how to make it rather efficient.
So I’m suggesting to add another Splitter.on...
method: Splitter.onAny(String...)
. Internally it could use regexes (that would make sense). Here’s my proposal:
public static Splitter onAny(String... separators) {
return onPattern(
Joiner.on("|").appendTo(new StringBuilder("(?:"), FluentIterable.from(separators).transform(Pattern::quote)).append(")").toString()
);
}
Or if you still don’t like inter-package dependencies (as I once or twice read):
public static Splitter onAny(String... separators) {
return onPattern(Arrays.stream(separators).map(Pattern::quote).collect(Collectors.joining("|", "(?:", ")"));
}
Issue Analytics
- State:
- Created 6 years ago
- Reactions:1
- Comments:6 (5 by maintainers)
Top GitHub Comments
That’s an excellent idea! Actually, this can be the one killer feature for
StringMatcher
we were looking for (see discussion of #2692), as I’ve noted in that ticket that the feature is rather moot, if not directly inferior to regexes.A potential alternative, if deemed desirable, would be
Splitter.on(StringMatcher.anyOf(String...))
, whereStringMatcher
would come from issues https://github.com/google/guava/issues/2692 and https://github.com/google/guava/issues/1075.