Java Top

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

> CHECK OUT THE COURSE

1. Overview

In this tutorial, we'll see how to use the useDelimiter method of the Scanner class.

2. Introduction to java.util.Scanner

The Scanner API provides a simple text scanner.

By default, a Scanner splits its input into tokens using white spaces as delimiters. Let's write a function that will:

  • pass input to a Scanner
  • iterate through the Scanner to gather the tokens in a list

Let's take a look at the basic implementation:

public static List<String> baseScanner(String input) {
    try (Scanner scan = new Scanner(input)) {
        List<String> result = new ArrayList<String>();
        scan.forEachRemaining(result::add);
        return result;
    }
}

Let's note that in this piece of code we've used a try-with-resources to create our Scanner. This is possible because the Scanner class implements the AutoCloseable interface. This block takes responsibility for closing the Scanner resource automatically. Before Java 7, we couldn't use try-with-resources and thus would have had to handle it manually.

We can also notice that in order to iterate on the Scanner elements, we've used the forEachRemaining method. This method was introduced in Java 8. Scanner implements Iterator, and we'd have to take advantage of that to iterate through the elements if we'd used an older Java version.

As we said, Scanner will use white spaces by default to parse its input. For instance, calling our baseScanner method with the following input: “Welcome to Baeldung”, should return a list containing the following ordered elements: “Welcome”, “to”, “Baeldung”.

Let's write a test to check that our method behaves as expected:

@Test
void whenBaseScanner_ThenWhitespacesAreUsedAsDelimiters() {
    assertEquals(List.of("Welcome", "to", "Baeldung"), baseScanner("Welcome to Baeldung"));
}

3. Use Custom Delimiters

Let's now set up our scanner to use a custom delimiter. We'll pass in a String which will be used by the Scanner to break the input.

Let's see how we can do that:

public static List<String> scannerWithDelimiter(String input, String delimiter) {
    try (Scanner scan = new Scanner(input)) {
        scan.useDelimiter(delimiter); 
        List<String> result = new ArrayList<String>();
        scan.forEachRemaining(result::add);
        return result;
    }
}

Let's comment on a couple of examples:

  • we can use a single character as a delimiter: the character must be escaped if needed. For instance, if we want to mimic the base behavior and use white spaces as delimiters, we'll use “\\s”
  • we can use any word/phrase as a delimiter
  • we can use multiple possible characters as delimiters: for this, we have to separate them with a |. For example, if we want to split input between every white space and every line break, we'll use the following delimiter: “\n|\\s”
  • in a nutshell, we can use any kind of regular expression as a delimiter: for instance, “a+” is a valid delimiter

Let's have a look at how we would test the first case:

@Test
void givenSimpleCharacterDelimiter_whenScannerWithDelimiter_ThenInputIsCorrectlyParsed() {
    assertEquals(List.of("Welcome", "to", "Baeldung"), scannerWithDelimiter("Welcome to Baeldung", "\\s"));
}

Actually, under the scene, the useDelimiter method will convert its input to a regular expression encapsulated in a Pattern object. Alternatively, we could also take care of the instantiation of the Pattern ourselves. For this we would need to use the overriding useDelimiter(Pattern pattern), as shown here:

public static List<String> scannerWithDelimiterUsingPattern(String input, Pattern delimiter) {
    try (Scanner scan = new Scanner(input)) {
        scan.useDelimiter(delimiter); 
        List<String> result = new ArrayList<String>();
        scan.forEachRemaining(result::add);
        return result;
    }
}

To instantiate a Pattern, we can use the compile method as in the following test:

@Test
void givenStringDelimiter_whenScannerWithDelimiterUsingPattern_ThenInputIsCorrectlyParsed() {
    assertEquals(List.of("Welcome", "to", "Baeldung"), DelimiterDemo.scannerWithDelimiterUsingPattern("Welcome to Baeldung", Pattern.compile("\\s")));
}

4. Conclusion

In this article, we've showcased a couple of examples of patterns that can be used to call the useDelimiter function. We noticed that by default, Scanner uses white space delimiters, and we pointed out that we could use any kind of regular expression there.

As always, the complete code is available over on GitHub.

Java bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE
Generic footer banner
Comments are closed on this article!