Java Scanner findWithinHorizon() Method

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

Definition

In Java, sc.findWithinHorizon(pattern, horizon) searches forward up to horizon characters—across line boundaries and ignoring delimiters—for the next match of pattern.

Passing horizon = 0 removes the character limit so the scanner searches all remaining input until a match is found or EOF is reached.

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.findWithinHorizon(...).

Syntax

Pass a regex String or Pattern together with a non-negative character limit (0 means unlimited).

Java
Scanner sc = new Scanner("Header\nID: B-99\nEnd");
String code = sc.findWithinHorizon("B-\\d+", 0);   // "B-99" (crossed newline)
CallWhat it does
sc.findWithinHorizon("B-\\d+", 0)Searches across all remaining lines (0 = no limit).
sc.findWithinHorizon(pattern, 50)Searches at most 50 characters ahead from the current cursor.
sc.match()Inspects match offsets and capture groups after a non-null result.

If a match starts inside the horizon window or extends past horizon characters from the current cursor, it is not matched until the window covers the full pattern.

Library declarations
Java
// java.util.Scanner
public String findWithinHorizon(Pattern pattern, int horizon)
public String findWithinHorizon(String pattern, int horizon)

Parameters

ParameterDescription
patternRegex String or compiled Pattern to locate.
horizonMaximum characters to inspect (0 for unlimited; negative values throw).

Return Value

Return ValueDescription
StringThe matched substring (advancing past it), or null if not found within the horizon.
Throws IllegalArgumentExceptionIf horizon < 0.
Throws IllegalStateExceptionIf the scanner is closed.

Compare with Similar Methods

Cross-line pattern search vs single-line and anchored skips:

MethodHow it differs
findInLine(p)Restricted to the current line; never crosses newlines.
skip(p)Requires the pattern right at the current position.
match()Exposes groups and positions of the found match.

Java Examples

Example 1 — Search Across Multiple Lines with Horizon 0

Locate an error tag two lines down without calling nextLine() manually.

Java
import java.util.Scanner;
import java.util.regex.Pattern;

public class ScannerFindHorizonZero {
    public static void main(String[] args) {
        String multi = "Boot log\nStatus: OK\nError: E-404\nDone";
        Pattern err = Pattern.compile("E-\\d+");
        try (Scanner sc = new Scanner(multi)) {
            String found = sc.findWithinHorizon(err, 0);
            System.out.println("Found across lines: " + found);
            System.out.println("Remaining text: [" + sc.next() + "]");
        }
    }
}

How It Works

  1. Horizon 0 searches everything. Passing 0 scans across both line breaks until "E-404" matches.
  2. Cursor advances past match. After returning "E-404", the cursor sits right after 404.
  3. Trailing token ready. Calling sc.next() skips the final newline and reads "Done".

Example 2 — Compare a Narrow Horizon Against a Wider One

See how a 10-character window misses "TARGET" without advancing, while a 20-character window finds it.

Java
import java.util.Scanner;

public class ScannerFindHorizonWindow {
    public static void main(String[] args) {
        String data = "1234567890TARGET";
        try (Scanner sc = new Scanner(data)) {
            System.out.println("Horizon 10: " + sc.findWithinHorizon("TARGET", 10));
            System.out.println("Horizon 15: " + sc.findWithinHorizon("TARGET", 15));
            System.out.println("Horizon 20: " + sc.findWithinHorizon("TARGET", 20));
        }
    }
}

How It Works

  1. Window stops before target. In "1234567890TARGET", the word starts at index 10 and ends at 16, so horizons 10 and 15 cut it short.
  2. Failed search keeps cursor at 0. Neither null result advances the cursor past 1234567890.
  3. Horizon 20 encompasses full match. Because 16 characters fit inside 20, the third call returns "TARGET".

Example 3 — Catch IllegalArgumentException for Negative Horizon Values

Verify that passing -1 throws IllegalArgumentException cleanly.

Java
import java.util.Scanner;

public class ScannerFindHorizonNegative {
    public static void main(String[] args) {
        try (Scanner sc = new Scanner("abc 123")) {
            try {
                sc.findWithinHorizon("\\d+", -1);
            } catch (IllegalArgumentException e) {
                System.out.println("Bad horizon threw: " + e.getClass().getSimpleName());
            }
            System.out.println("Fallback with 0: " + sc.findWithinHorizon("\\d+", 0));
        }
    }
}

How It Works

  1. Negative horizons disallowed. Passing -1 fails argument validation before any scanning happens.
  2. Scanner stays usable. Catching IllegalArgumentException leaves the scanner open and at position 0.
  3. Zero succeeds afterwards. Switching the horizon to 0 locates "123" immediately.

Frequently Asked Questions

It means no character limit: search across all remaining input until a match is found or the stream ends.
findInLine() stops at the next line separator, while findWithinHorizon() searches across line breaks up to the horizon count.
IllegalArgumentException.
No. It ignores delimiters, just like findInLine().
It returns null and leaves the scanner position unchanged.

Next: hasNext()

Check whether another token is available without consuming it.

hasNext() 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.

10 people found this page helpful