Java Scanner useDelimiter() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
java.util.Scanner

Definition

In Java, sc.useDelimiter(pattern) changes how the scanner splits input into tokens and returns the Scanner itself so calls can be chained.

You can pass either a regex String (compiled automatically) or a precompiled Patternβ€”for instance "\\s*,\\s*" to trim spaces around CSV commas.

An instance method of java.util.Scanner, available since Java 5 (JDK 1.5). A Scanner reads from any source (System.in for keyboard, a String, or a file) with identical parsing logic; pass the source to new Scanner(...) after import java.util.Scanner; and call sc.useDelimiter(...).

Syntax

Chain useDelimiter(...) right onto new Scanner(...), or call it mid-stream to change separators.

Java
Scanner sc = new Scanner("Ada, 95 , Bob").useDelimiter("\\s*,\\s*");
String name = sc.next();      // "Ada"
int score = sc.nextInt();     // 95
CallWhat it does
sc.useDelimiter(",")Splits on every single comma (adjacent commas produce an empty token).
sc.useDelimiter("\\s*,\\s*")Splits on commas and trims surrounding spaces/newlines.
sc.useDelimiter(pattern)Applies a compiled Pattern and returns this.

Because useDelimiter(",") matches exactly one comma, "a,,c" yields "a", "", and "c". Use ",+" if you want consecutive commas to collapse.

Library declarations
Java
// java.util.Scanner
public Scanner useDelimiter(Pattern pattern)
public Scanner useDelimiter(String pattern)

Parameters

ParameterDescription
patternRegex String or compiled Pattern matching separators between tokens.

Return Value

Return ValueDescription
ScannerThe same scanner instance, enabling method chaining like sc.useDelimiter(",").useLocale(Locale.US).
Throws PatternSyntaxExceptionIf a String argument is not valid regex syntax.
ThrowsNothing. It does not check whether the scanner is closed.

Compare with Similar Methods

Delimiter control and alternatives:

MethodHow it differs
delimiter()Reads back the active delimiter Pattern.
reset()Restores delimiter, locale, and radix to defaults.
String.split()Splits a single already-read line into a String[].
skip(p)Skips a specific prefix without altering the delimiter.

Java Examples

Example 1 — Parse Comma-Separated Values While Trimming Spaces

Use the "\\s*,\\s*" regex idiom so spaces around commas disappear automatically.

Java
import java.util.Scanner;

public class ScannerUseDelimiterCsv {
    public static void main(String[] args) {
        String row = "Ada , 95 , Bob , 88";
        try (Scanner sc = new Scanner(row).useDelimiter("\\s*,\\s*")) {
            while (sc.hasNext()) {
                String name = sc.next();
                int score = sc.nextInt();
                System.out.println(name + " scored " + score);
            }
        }
    }
}

How It Works

  1. Surrounding whitespace consumed. \\s*,\\s* eats any spaces before and after each comma, keeping tokens clean.
  2. Numeric parse succeeds directly. Because spaces around 95 were eaten as delimiter, nextInt() parses 95 without throwing.
  3. Chained setup. Calling .useDelimiter(...) right on new Scanner(...) configures the scanner in one expression.

Example 2 — See Empty Tokens Between Adjacent Commas vs Collapsing

Compare "," (preserves blank CSV cells) with ",+" (skips repeated commas).

Java
import java.util.Scanner;

public class ScannerUseDelimiterEmpty {
    public static void main(String[] args) {
        try (Scanner strict = new Scanner("a,,c").useDelimiter(",")) {
            while (strict.hasNext()) {
                System.out.println("Strict: [" + strict.next() + "]");
            }
        }
        try (Scanner collapsed = new Scanner("a,,c").useDelimiter(",+")) {
            while (collapsed.hasNext()) {
                System.out.println("Collapsed: [" + collapsed.next() + "]");
            }
        }
    }
}

How It Works

  1. Single comma leaves empty cell. With ",", the zero characters between the two commas become "".
  2. Quantifier merges delimiters. Changing to ",+" treats ",," as one separator, omitting the blank token.
  3. Trailing comma edge. Note that a single trailing comma at the very end of input does not create a trailing blank token.

Example 3 — Handle Line Breaks in Multi-Line CSV Input

Avoid merging the last column of row 1 with the first column of row 2 by including line breaks in the delimiter.

Java
import java.util.Scanner;

public class ScannerUseDelimiterLines {
    public static void main(String[] args) {
        String table = "10,20\n30,40";
        try (Scanner sc = new Scanner(table).useDelimiter("[,\\r\\n]+")) {
            int total = 0;
            while (sc.hasNextInt()) {
                total += sc.nextInt();
            }
            System.out.println("Table sum: " + total);
        }
    }
}

How It Works

  1. Include newline characters in regex. [,\r\n]+ treats commas, carriage returns, and line feeds alike as separators.
  2. Prevents merged tokens. With plain ",", 20\n30 would be one token and fail nextInt().
  3. Clean integer loop. All four numbers parse into 10 + 20 + 30 + 40 = 100.

Frequently Asked Questions

It returns the Scanner object itself, allowing you to chain calls like new Scanner(text).useDelimiter(",").useLocale(Locale.US).
Because "," matches only the comma character, not spaces. Use "\s*,\s*" to remove surrounding spaces too.
Because "," matches one comma at a time, so the zero characters between two commas form an empty token "".
Custom delimiters replace whitespace, so newlines are no longer skipped. Include \r\n in your delimiter or read lines with nextLine() first.
Yes. Overloads accept either a String regex or a java.util.regex.Pattern.

Next: useLocale()

Change the Locale used to parse decimal and grouping separators.

useLocale() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P πŸ”—

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

13 people found this page helpful