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

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.
Tokenizers in the JDK
ToolSinceBoundariesBest for
String.splitJava 1.4A regex; keeps empty fieldsDelimited fields; see splitting strings
ScannerJava 5A regex, whitespace by defaultReading typed values from text or input
StringTokenizerJava 1.0, legacyA set of characters; skips empty tokensOld code; simple whitespace splitting
StreamTokenizerJava 1.0Character classes: words, numbers, quotes, commentsSimple configuration files and command languages
Matcher.find with alternativesJava 1.4One regex per token typeSmall expression languages and query parsers
Hand-written state machineAnyWhatever the rules needQuoted CSV and other formats with escapes
BreakIterator.getWordInstanceJava 1.1Unicode word rulesWords in human language

The StringTokenizer documentation calls it a legacy class kept for compatibility and recommends split or java.util.regex for new code. The programs below ran on JDK 21.

Scanner: typed tokens

Scanner reads tokens and converts them to int, double, boolean and other types. The input is two records with four typed fields each, followed by inputs that show its three classic traps.

Java
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:

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, nextDouble and nextBoolean read one token each, skipping the whitespace between them, so both records were read in a loop without any splitting.
  • With useDelimiter(";"), the empty token between ;; is returned as an empty string. hasNextInt checks the type before reading, so x and the empty token were skipped and the numbers summed to 80.
  • The trap most beginners hit: nextInt stops after 42 and leaves the line break, so the following nextLine returns the empty rest of that line. Call nextLine() once more, or read whole lines and parse them.
  • Scanner reads numbers in its locale, which defaults to the system's. With a German locale, 72.5 threw InputMismatchException and 1.234,5 was read as 1234.5. Use useLocale(Locale.ROOT) for machine-written data, as the first block does.
  • findInLine searches for a regex in the current line, ignoring the delimiter, here the order code A-1042.

StringTokenizer and how it differs from split

StringTokenizer appears in a lot of older code and in competitive programming, and its rules are different enough from split to cause bugs when code is converted. The input has two adjacent commas, a second delimiter and a trailing comma.

Java
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:

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
  • StringTokenizer never returns empty tokens, so a,,b;c, gave three. split kept the empty field between the commas, and with -1 also the trailing one. For records with optional fields, StringTokenizer silently shifts the columns.
  • Its delimiter argument is a set of characters, not a string: "ab" means "a or b", so xaybz became x, y and z. split("ab") looks for the sequence ab and found none.
  • With returnDelims set to true, the delimiters come back as tokens, which is enough to tokenize a simple arithmetic expression.
  • nextToken(String) changes the delimiters for this and later calls. After reading key up to =, the next token up to ; started at the = itself, giving =a value: the delimiter was not consumed.

StreamTokenizer: words, numbers, strings and comments

StreamTokenizer classifies characters as word characters, digits, quotes, comment starters or whitespace, and returns typed tokens with line numbers. It suits simple configuration formats, so the test input is a small settings file with two kinds of comments and two kinds of quotes.

Java
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:

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 lineno() reports where each token was, which is useful for error messages.
  • Numbers come back as double in nval, so the port is 8080.0, and -0.75 was read as one negative number, because - 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 ttype is the character itself.

Its rules are fixed and a little dated: numbers are always double, and it does not handle Unicode identifiers or escapes well. For anything more than simple settings, use a regex lexer or a parser library.

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.

Java
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:

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 find(pos) must match exactly at pos; otherwise an unexpected character is reported with its position, as the # at 6 was.
  • The named group that is not null says which kind of token matched, and start(group) gives its position, ready for error messages.
  • Order matters in alternation: >= is listed before >, or >= would lex as two tokens. Keywords come before names, with \b so that a name such as android is not lexed as the keyword followed by roid.
  • The string pattern '(?:[^']|'')*' accepts the SQL-style escape '', so 'O''Brien' is one token.

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.

Java
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:

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
  • split(",", -1) 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, with "" 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, but punctuation, contractions, prices and languages written without spaces break the simple approaches. The English test sentence contains all of the first three, and a Japanese sentence covers the last.

Java
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:

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: [私, は, 学生, です]
  • split("\\W+") broke Don't into Don and t, naïve into na and ve (because \W is ASCII-only), and the price into 3 and 50.
  • split("\\s+") kept every word whole but left punctuation attached: panic:, $3.50, and faster!.
  • BreakIterator.getWordInstance applies the Unicode word-boundary rules. It kept Don't, naïve and 3.50 together and separated the punctuation, which the helper then drops.
  • Japanese has no spaces between words, so split returned the whole sentence. The Japanese word instance found four words, using a dictionary in the JDK.

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.

Java
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):

Output
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
  • StringTokenizer 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.
  • A precompiled Matcher with \S+ came second, two to three times slower. split("\\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.
  • StreamTokenizer does more classification per character and converts numbers to double.
  • Scanner 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.

Which tokenizer to use

Choosing a tokenizer
InputUse
Fields separated by a delimitersplit(regex, -1)
Whitespace-separated words, large volumesStringTokenizer or a precompiled Matcher
Typed values from the console or a small fileScanner with useLocale(Locale.ROOT)
Simple settings with comments and quotesStreamTokenizer
A small expression or query languageA regex lexer with named groups
CSV with quotesA state machine, or better, a CSV library
Words in human languageBreakIterator.getWordInstance(locale)
JSON, XML, YAMLA real parser library, never a tokenizer

To join tokens back into a string, see joining strings.