Java Utility Library

Java Scanner - useDelimiter() Method



The java.util.Scanner.useDelimiter() method is used to set the scanner's delimiting pattern to the specified pattern. Invoking the reset() method will set the scanner's delimiter pattern to the default.

Syntax

public Scanner useDelimiter(Pattern pattern)

Parameters

pattern Specify the delimiting pattern.

Return Value

Returns the scanner.

Exception

NA.

Example:

In the example below, the java.util.Scanner.useDelimiter() method is used to set the scanner's delimiting pattern to the specified pattern.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {

    //String to scan
    String MyString = "Hello#@Cello#@Hullo#@Hallo#@Jello";

    //creating a Scanner
    Scanner MyScan = new Scanner(MyString);

    //sets the scanner's delimiting pattern
    MyScan.useDelimiter(".@");

    while(MyScan.hasNext()) {
      //print the next token if matches if specified pattern
      System.out.println(MyScan.next());
    }
      
    //print the new delimiter
    System.out.println("New delimiter: "+ MyScan.delimiter());

    //close the scanner
    MyScan.close();
  }
}

The output of the above code will be:

Hello
Cello
Hullo
Hallo
Jello
New delimiter: .@

❮ Java.util - Scanner