Java Utility Library

Java Scanner - findWithinHorizon() Method



The java.util.Scanner.findWithinHorizon() method attempts to find the next occurrence of the specified pattern. This method searches through the input up to the specified search horizon, ignoring delimiters. If the pattern is found the scanner advances past the input that matched and returns the string that matched the pattern. If no such pattern is detected then the null is returned and the scanner's position remains unchanged. This method may block waiting for input that matches the pattern.

A scanner will never search more than horizon code points beyond its current position. Note that a match may be clipped by the horizon; that is, an arbitrary match result may have been different if the horizon had been larger.

Syntax

public String findWithinHorizon(Pattern pattern, int horizon)

Parameters

pattern Specify the pattern to scan for.
horizon Specify the search horizon.

Return Value

Returns the text that matched the specified pattern.

Exception

  • Throws IllegalStateException, if the scanner is closed.
  • Throws IllegalArgumentException, if horizon is negative.

Example:

In the example below, the java.util.Scanner.findWithinHorizon() method returns next occurrence of the specified pattern, ignoring delimiters and within given horizon.

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);

    //print five word pattern that ends with ullo, with horizon 10
    System.out.println(MyScan.findWithinHorizon(".ullo", 10));

    //print five word pattern that ends with ullo, with horizon 20
    System.out.println(MyScan.findWithinHorizon(".ullo", 20));

    //prints the remaining portion of the line
    System.out.println(MyScan.nextLine()); 

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

The output of the above code will be:

null
Hullo
 Hallo Jello

❮ Java.util - Scanner