String Tokenizing
Tokenizing breaks text into meaningful pieces such as words, numbers, operators and fields. Java has several tokenizers with different rules: split for delimited fields, Scanner for typed values, the legacy StringTokenizer, StreamTokenizer for simple languages, regex lexers, and BreakIterator for natural language. This page shows what each does with the same kinds of input and how fast it is.
Contents
What a tokenizer does Scanner: typed tokens StringTokenizer and how it differs from split StreamTokenizer: words, numbers, strings and comments A regex lexer for a small query language Quoted CSV needs a real parser Words in human language: BreakIterator How fast is each tokenizer? Which tokenizer to use
What a tokenizer does
A token is the smallest piece of text that means something to the program reading it: a word, a number, an operator, a field of a record. A tokenizer, also called a lexer, scans the text once from left to right and returns tokens one at a time, often with a type such as "number" or "word". The tokenizers in the JDK differ in three ways:
- How a boundary is defined: a set of delimiter characters, a regular expression, or rules about which characters may form a token.
- Whether empty tokens between two delimiters are kept, which matters for records with empty fields.
- Whether tokens come back as plain strings or are converted to typed values.
| Tool | Since | Boundaries | Best for |
|---|---|---|---|
String.split | Java 1.4 | A regex; keeps empty fields | Delimited fields; see |
Scanner | Java 5 | A regex, whitespace by default | Reading typed values from text or input |
StringTokenizer | Java 1.0, legacy | A set of characters; skips empty tokens | Old code; simple whitespace splitting |
StreamTokenizer | Java 1.0 | Character classes: words, numbers, quotes, comments | Simple configuration files and command languages |
Matcher.find | Java 1.4 | One regex per token type | Small expression languages and query parsers |
| Hand-written state machine | Any | Whatever the rules need | Quoted CSV and other formats with escapes |
BreakIterator.getWordInstance | Java 1.1 | Unicode word rules | Words in human language |
The StringTokenizersplitjava.util.regex
Scanner: typed tokens
Scannerintdoubleboolean
import java.util.InputMismatchException;
import java.util.Locale;
import java.util.Scanner;
public class ScannerTokens {
public static void main(String[] args) {
String input = "ann 34 72.5 true\nbob 29 81.0 false\n";
// Scanner reads typed tokens; whitespace is the default delimiter
try (Scanner sc = new Scanner(input).useLocale(Locale.ROOT)) {
while (sc.hasNext()) {
String name = sc.next();
int age = sc.nextInt();
double weight = sc.nextDouble();
boolean member = sc.nextBoolean();
System.out.println(name + " is " + age + ", " + weight + " kg, member=" + member);
}
}
// A custom delimiter, and checking the type before reading
try (Scanner sc = new Scanner("10;x;30;;40").useDelimiter(";")) {
int sum = 0;
while (sc.hasNext()) {
if (sc.hasNextInt()) {
sum += sc.nextInt();
} else {
System.out.println("skipping token [" + sc.next() + "]");
}
}
System.out.println("sum = " + sum);
}
// The nextLine trap: nextInt leaves the line break behind
try (Scanner sc = new Scanner("42\nAda Lovelace\n")) {
int id = sc.nextInt();
String name = sc.nextLine();
System.out.println("id=" + id + ", name=[" + name + "] (the rest of the first line)");
System.out.println("next nextLine() = [" + sc.nextLine() + "]");
}
// Numbers follow the Scanner's locale
try (Scanner sc = new Scanner("72.5").useLocale(Locale.GERMANY)) {
sc.nextDouble();
} catch (InputMismatchException e) {
System.out.println("German locale, \"72.5\": InputMismatchException");
}
try (Scanner sc = new Scanner("1.234,5").useLocale(Locale.GERMANY)) {
System.out.println("German locale, \"1.234,5\": " + sc.nextDouble());
}
// findInLine searches with a regex, ignoring delimiters
try (Scanner sc = new Scanner("order #A-1042 shipped")) {
System.out.println("findInLine: " + sc.findInLine("[A-Z]-\\d+"));
}
}
}
Output:
ann is 34, 72.5 kg, member=true
bob is 29, 81.0 kg, member=false
skipping token [x]
skipping token []
sum = 80
id=42, name=[] (the rest of the first line)
next nextLine() = [Ada Lovelace]
German locale, "72.5": InputMismatchException
German locale, "1.234,5": 1234.5
findInLine: A-1042
,next ,nextInt andnextDouble read one token each, skipping the whitespace between them, so both records were read in a loop without any splitting.nextBoolean- With
, the empty token betweenuseDelimiter(";") is returned as an empty string.;; checks the type before reading, sohasNextInt and the empty token were skipped and the numbers summed to 80.x - The trap most beginners hit:
stops afternextInt and leaves the line break, so the following42 returns the empty rest of that line. CallnextLine once more, or read whole lines and parse them.nextLine() reads numbers in its locale, which defaults to the system's. With a German locale,Scanner threw72.5 andInputMismatchException was read as 1234.5. Use1.234,5 for machine-written data, as the first block does.useLocale(Locale.ROOT) searches for a regex in the current line, ignoring the delimiter, here the order codefindInLine .A-1042
StringTokenizer and how it differs from split
StringTokenizersplit
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
public class TokenizerVsSplit {
public static void main(String[] args) {
String line = "a,,b;c,";
// StringTokenizer: each character in the delimiter string is a delimiter,
// and empty tokens are skipped
System.out.println("StringTokenizer: " + tokens(new StringTokenizer(line, ",;")));
// split keeps the empty field between the two commas, and -1 keeps the last one
System.out.println("split(\"[,;]\"): " + Arrays.toString(line.split("[,;]")));
System.out.println("split(\"[,;]\", -1): " + Arrays.toString(line.split("[,;]", -1)));
// The delimiter string is a set of characters, not a sequence
System.out.println("delims \"ab\" on \"xaybz\": "
+ tokens(new StringTokenizer("xaybz", "ab")));
System.out.println("split(\"ab\") on \"xaybz\": " + Arrays.toString("xaybz".split("ab")));
// returnDelims = true hands back the delimiters as tokens too
System.out.println("with delimiters: "
+ tokens(new StringTokenizer("3+4*2", "+*", true)));
// The delimiters can change between calls
StringTokenizer st = new StringTokenizer("key=a value;b c");
System.out.println("nextToken(\"=\"): " + st.nextToken("="));
System.out.println("nextToken(\";\"): " + st.nextToken(";"));
System.out.println("countTokens(): " + st.countTokens());
}
static List<String> tokens(StringTokenizer st) {
List<String> out = new ArrayList<>();
while (st.hasMoreTokens()) {
out.add(st.nextToken());
}
return out;
}
}
Output:
StringTokenizer: [a, b, c]
split("[,;]"): [a, , b, c]
split("[,;]", -1): [a, , b, c, ]
delims "ab" on "xaybz": [x, y, z]
split("ab") on "xaybz": [xaybz]
with delimiters: [3, +, 4, *, 2]
nextToken("="): key
nextToken(";"): =a value
countTokens(): 1
never returns empty tokens, soStringTokenizer gave three.a,,b;c, kept the empty field between the commas, and withsplit also the trailing one. For records with optional fields,-1 silently shifts the columns.StringTokenizer- Its delimiter argument is a set of characters, not a string:
means "a or b", so"ab" becamexaybz ,x andy .z looks for the sequencesplit("ab") and found none.ab - With
set to true, the delimiters come back as tokens, which is enough to tokenize a simple arithmetic expression.returnDelims changes the delimiters for this and later calls. After readingnextToken(String) up tokey , the next token up to= started at the; itself, giving= : the delimiter was not consumed.=a value
StreamTokenizer: words, numbers, strings and comments
StreamTokenizer
import java.io.IOException;
import java.io.StreamTokenizer;
import java.io.StringReader;
public class StreamTokens {
public static void main(String[] args) throws IOException {
String config = """
# server settings
port = 8080
host = "example.com" // inline comment
ratio = -0.75
name = 'my app'
""";
StreamTokenizer t = new StreamTokenizer(new StringReader(config));
t.commentChar('#'); // '#' starts a comment to the end of the line
t.slashSlashComments(true); // and so does //
t.quoteChar('\''); // single quotes delimit strings too ('"' already does)
while (t.nextToken() != StreamTokenizer.TT_EOF) {
String kind = switch (t.ttype) {
case StreamTokenizer.TT_WORD -> "WORD " + t.sval;
case StreamTokenizer.TT_NUMBER -> "NUMBER " + t.nval;
case '"', '\'' -> "STRING " + t.sval;
default -> "CHAR " + (char) t.ttype;
};
System.out.println("line " + t.lineno() + ": " + kind);
}
}
}
Output:
line 2: WORD port
line 2: CHAR =
line 2: NUMBER 8080.0
line 3: WORD host
line 3: CHAR =
line 3: STRING example.com
line 4: WORD ratio
line 4: CHAR =
line 4: NUMBER -0.75
line 5: WORD name
line 5: CHAR =
line 5: STRING my app
- The comment line and the
comment produced no tokens at all, and// reports where each token was, which is useful for error messages.lineno() - Numbers come back as
indouble , so the port isnval , and8080.0 was read as one negative number, because-0.75 is part of number parsing by default.- - Quoted text in either kind of quote becomes one token with the quotes removed, including the space in
.my app - Any other character, such as
, is returned as a single-character token whose= is the character itself.ttype
Its rules are fixed and a little dated: numbers are always double
A regex lexer for a small query language
When a format has several kinds of tokens, one regex with a named group per kind makes a compact lexer. The test input is a filter expression with numbers, keywords, names, a quoted string with an escaped quote, and two-character operators.
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexLexer {
record Token(String type, String text, int pos) {
}
// One alternative per token type; the order matters (>= before >, keywords before names)
static final Pattern TOKENS = Pattern.compile(
"\\s*(?:(?<number>\\d+(?:\\.\\d+)?)|(?<keyword>\\b(?:and|or|not)\\b)"
+ "|(?<name>[A-Za-z_]\\w*)|(?<string>'(?:[^']|'')*')|(?<op>>=|<=|!=|[=<>()]))");
static List<Token> lex(String input) {
List<Token> out = new ArrayList<>();
Matcher m = TOKENS.matcher(input);
int pos = 0;
while (pos < input.length()) {
if (!m.find(pos) || m.start() != pos) {
if (input.substring(pos).isBlank()) {
break;
}
throw new IllegalArgumentException("unexpected '" + input.charAt(skip(input, pos))
+ "' at " + skip(input, pos));
}
for (String type : new String[] {"number", "keyword", "name", "string", "op"}) {
if (m.group(type) != null) {
out.add(new Token(type, m.group(type), m.start(type)));
}
}
pos = m.end();
}
return out;
}
static int skip(String s, int pos) {
while (pos < s.length() && Character.isWhitespace(s.charAt(pos))) {
pos++;
}
return pos;
}
public static void main(String[] args) {
String query = "price >= 10.5 and (name = 'O''Brien' or not active)";
for (Token t : lex(query)) {
System.out.printf("%-8s %-12s at %d%n", t.type(), t.text(), t.pos());
}
try {
lex("price # 3");
} catch (IllegalArgumentException e) {
System.out.println("error: " + e.getMessage());
}
}
}
Output:
name price at 0
op >= at 6
number 10.5 at 9
keyword and at 14
op ( at 18
name name at 19
op = at 24
string 'O''Brien' at 26
keyword or at 37
keyword not at 40
name active at 44
op ) at 50
error: unexpected '#' at 6
- Each call to
must match exactly atfind(pos) ; otherwise an unexpected character is reported with its position, as thepos at 6 was.# - The named group that is not null says which kind of token matched, and
gives its position, ready for error messages.start(group) - Order matters in alternation:
is listed before>= , or> would lex as two tokens. Keywords come before names, with>= so that a name such as\b is not lexed as the keyword followed byandroid .roid - The string pattern
accepts the SQL-style escape'(?:[^']|'')*' , so'' is one token.'O''Brien'
Quoted CSV needs a real parser
CSV fields may be quoted, and quoted fields may contain commas and doubled quotes. No delimiter-based tokenizer can handle that, because whether a comma is a delimiter depends on what came before it. The test line has all of these cases plus an empty last field.
import java.util.ArrayList;
import java.util.List;
public class CsvLine {
// split(",") breaks on commas inside quotes; a small state machine does not
static List<String> parse(String line) {
List<String> fields = new ArrayList<>();
StringBuilder current = new StringBuilder();
boolean inQuotes = false;
for (int i = 0; i < line.length(); i++) {
char c = line.charAt(i);
if (c == '"') {
if (inQuotes && i + 1 < line.length() && line.charAt(i + 1) == '"') {
current.append('"'); // "" inside quotes is a literal quote
i++;
} else {
inQuotes = !inQuotes;
}
} else if (c == ',' && !inQuotes) {
fields.add(current.toString());
current.setLength(0);
} else {
current.append(c);
}
}
if (inQuotes) {
throw new IllegalArgumentException("unclosed quote in: " + line);
}
fields.add(current.toString());
return fields;
}
public static void main(String[] args) {
String line = "42,\"Smith, Jane\",\"said \"\"hi\"\"\",";
show("split(\",\")", List.of(line.split(",", -1)));
show("parse()", parse(line));
show("empty fields", parse(",,"));
show("spaces kept", parse(" a , \"b\" "));
try {
parse("1,\"open");
} catch (IllegalArgumentException e) {
System.out.println("error: " + e.getMessage());
}
}
// Print each field in brackets so the boundaries are visible
static void show(String label, List<String> fields) {
StringBuilder sb = new StringBuilder();
for (String f : fields) {
sb.append('[').append(f).append(']');
}
System.out.printf("%-12s %d fields: %s%n", label, fields.size(), sb);
}
}
Output:
split(",") 5 fields: [42]["Smith][ Jane"]["said ""hi"""][]
parse() 4 fields: [42][Smith, Jane][said "hi"][]
empty fields 3 fields: [][][]
spaces kept 2 fields: [ a ][ b ]
error: unclosed quote in: 1,"open
cut the name at its comma and kept the quotes, giving 5 broken fields. The state machine tracks whether it is inside quotes and returned the 4 real fields, withsplit(",", -1) turned into one quote."" gives three empty fields, and spaces around fields are kept, which is what RFC 4180 specifies.,,- An unclosed quote is an error worth reporting rather than silently accepting.
- Real CSV files also have quoted fields that contain line breaks, so a parser must read across lines. For production data, use a library such as Apache Commons CSV or OpenCSV.
Words in human language: BreakIterator
Splitting prose into words looks like a job for split
import java.text.BreakIterator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
public class WordTokens {
public static void main(String[] args) {
String text = "Don't panic: the na\u00EFve fix costs $3.50, e.g. 2x faster!";
System.out.println("split(\"\\\\W+\"): " + Arrays.toString(text.split("\\W+")));
System.out.println("split(\"\\\\s+\"): " + Arrays.toString(text.split("\\s+")));
System.out.println("BreakIterator: " + words(text, Locale.ENGLISH));
// Words in a language written without spaces
String japanese = "\u79C1\u306F\u5B66\u751F\u3067\u3059"; // "I am a student"
System.out.println("split on spaces: " + Arrays.toString(japanese.split("\\s+")));
System.out.println("BreakIterator ja: " + words(japanese, Locale.JAPANESE));
}
// Word tokens only: segments that contain at least one letter or digit
static List<String> words(String text, Locale locale) {
BreakIterator it = BreakIterator.getWordInstance(locale);
it.setText(text);
List<String> out = new ArrayList<>();
int start = it.first();
for (int end = it.next(); end != BreakIterator.DONE; start = end, end = it.next()) {
String piece = text.substring(start, end);
if (piece.codePoints().anyMatch(Character::isLetterOrDigit)) {
out.add(piece);
}
}
return out;
}
}
Output:
split("\\W+"): [Don, t, panic, the, na, ve, fix, costs, 3, 50, e, g, 2x, faster]
split("\\s+"): [Don't, panic:, the, naïve, fix, costs, $3.50,, e.g., 2x, faster!]
BreakIterator: [Don't, panic, the, naïve, fix, costs, $3.50, e.g, 2x, faster]
split on spaces: [私は学生です]
BreakIterator ja: [私, は, 学生, です]
brokesplit("\\W+") intoDon't andDon ,t intonaïve andna (becauseve is ASCII-only), and the price into 3 and 50.\W kept every word whole but left punctuation attached:split("\\s+") ,panic: and$3.50, .faster! applies the Unicode word-boundary rules. It keptBreakIterator.getWordInstance ,Don't andnaïve together and separated the punctuation, which the helper then drops.3.50- Japanese has no spaces between words, so
returned the whole sentence. The Japanese word instance found four words, using a dictionary in the JDK.split
How fast is each tokenizer?
The program counts the 800,000 whitespace-separated tokens in a 5 MB text with each tool, keeping the fastest of three runs.
import java.io.IOException;
import java.io.StreamTokenizer;
import java.io.StringReader;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TokenSpeed {
static final Pattern WORD = Pattern.compile("\\S+");
public static void main(String[] args) throws IOException {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 200000; i++) {
sb.append("user").append(i).append(" 42 active north\n");
}
String text = sb.toString();
System.out.printf("count whitespace-separated tokens in %,d chars%n", text.length());
time("split(\"\\\\s+\")", () -> text.split("\\s+").length);
time("StringTokenizer", () -> {
StringTokenizer st = new StringTokenizer(text);
int n = 0;
while (st.hasMoreTokens()) {
st.nextToken();
n++;
}
return n;
});
time("Matcher.find(\\S+)", () -> {
Matcher m = WORD.matcher(text);
int n = 0;
while (m.find()) {
m.group();
n++;
}
return n;
});
time("Scanner.next", () -> {
int n = 0;
try (Scanner sc = new Scanner(text)) {
while (sc.hasNext()) {
sc.next();
n++;
}
}
return n;
});
time("StreamTokenizer", () -> {
StreamTokenizer t = new StreamTokenizer(new StringReader(text));
int n = 0;
try {
while (t.nextToken() != StreamTokenizer.TT_EOF) {
n++;
}
} catch (IOException e) {
throw new IllegalStateException(e);
}
return n;
});
}
interface Count {
int run();
}
// Best of 3 runs
static void time(String name, Count c) {
long best = Long.MAX_VALUE;
int tokens = 0;
for (int r = 0; r < 3; r++) {
long t0 = System.nanoTime();
tokens = c.run();
best = Math.min(best, System.nanoTime() - t0);
}
System.out.printf("%-20s %7.1f ms %,d tokens%n", name, best / 1e6, tokens);
}
}
Output (rough comparison; 2-CPU Linux, JDK 21, times vary between runs):
count whitespace-separated tokens in 5,288,890 chars
split("\\s+") 126.0 ms 800,000 tokens
StringTokenizer 13.4 ms 800,000 tokens
Matcher.find(\S+) 35.6 ms 800,000 tokens
Scanner.next 163.1 ms 800,000 tokens
StreamTokenizer 96.9 ms 800,000 tokens
was the fastest. It checks each character against a small set of delimiters and allocates only the tokens, which is why it remains popular in programming contests despite being legacy.StringTokenizer- A precompiled
withMatcher came second, two to three times slower.\S+ was several times slower, because it builds a list and an array of all 800,000 tokens at once and its regex has no fast path.split("\\s+") does more classification per character and converts numbers toStreamTokenizer .double was the slowest: it matches every token against regular expressions and supports type conversion and locales. That overhead is fine for reading user input, not for bulk data.Scanner
Which tokenizer to use
| Input | Use |
|---|---|
| Fields separated by a delimiter | split(regex, -1) |
| Whitespace-separated words, large volumes | StringTokenizerMatcher |
| Typed values from the console or a small file | ScanneruseLocale(Locale.ROOT) |
| Simple settings with comments and quotes | StreamTokenizer |
| A small expression or query language | A regex lexer with named groups |
| CSV with quotes | A state machine, or better, a CSV library |
| Words in human language | BreakIterator.getWordInstance(locale) |
| JSON, XML, YAML | A real parser library, never a tokenizer |
To join tokens back into a string, see