Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Java

Idiom #259 Split on several separators

Build the list parts consisting of substrings of the input string s, separated by any of the characters ',' (comma), '-' (dash), '_' (underscore).

import static java.util.regex.Pattern.quote;
import java.util.Scanner;
Scanner t = new Scanner(s);
String z = quote(",-_");
z = "[%s]".formatted(z);
t.useDelimiter(compile(z));
String parts[] = t.tokens()
    .toArray(String[]::new);
t.close();
import static java.util.regex.Pattern.quote;
String z = "[%s]".formatted(quote(",-_")),
       parts[] = s.split(z, -1);
import static java.util.Collections.list;
import java.util.List;
import java.util.StringTokenizer;
List<?> parts = list(new StringTokenizer(s, ",-_"));

You can use `Object` or the `?` wildcard here,
the `StringTokenizer` class implements `Enumeration<Object>`.
var parts = s.Split(',', '-', '_');

New implementation...
< >
programming-idioms.org