Java Scanner findInLine() Method

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

Definition

In Java, sc.findInLine(pattern) searches forward from the current position only up to the next line separator for the next substring matching pattern, ignoring any token delimiters.

If a match is found, it advances past the match and returns the matched String. If no match appears on the rest of the current line, it returns null and leaves the scanner's position unchanged.

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

Syntax

Pass a regex String or compiled Pattern to search anywhere within the current line.

Java
Scanner sc = new Scanner("Order #402 total $19.50");
String id = sc.findInLine("#\\d+");        // "#402"
String price = sc.findInLine("\\d+\\.\\d+"); // "19.50"
CallWhat it does
sc.findInLine("#\\d+")Finds the first match on the current line, ignoring spaces/delimiters.
sc.findInLine(pattern)Same search using a precompiled Pattern.
sc.match()Inspects capture groups from the last non-null findInLine() call.

Because findInLine() never crosses a line break, it stops when it reaches \n or \r\n. Call nextLine() to move onto the next line before searching again.

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

Parameters

ParameterDescription
patternA regex String or compiled Pattern to search for on the current line.

Return Value

Return ValueDescription
StringThe matched substring if found on the current line; otherwise null.
Throws IllegalStateExceptionIf the scanner has been closed.
Throws PatternSyntaxExceptionIf a String pattern contains invalid regex syntax.

Compare with Similar Methods

Searching without delimiters vs delimiter-based reads:

MethodHow it differs
findWithinHorizon(p, h)Can cross line breaks up to h characters (or 0 for unlimited).
skip(p)Matches only right at the cursor; throws if missing.
next(p)Requires the whole delimited token to match p.
match()Reads capture groups from the match just found.

Java Examples

Example 1 — Pull an Order ID and Price Out of a Sentence

Ignore surrounding prose and delimiters on a single line using two findInLine() calls.

Java
import java.util.Scanner;

public class ScannerFindInLineExtract {
    public static void main(String[] args) {
        String note = "Order #402 shipped; total $19.50 today";
        try (Scanner sc = new Scanner(note)) {
            String orderId = sc.findInLine("#\\d+");
            String amount = sc.findInLine("\\d+\\.\\d+");
            System.out.println("ID: " + orderId);
            System.out.println("Amount: " + amount);
            System.out.println("Rest of line: [" + sc.nextLine().trim() + "]");
        }
    }
}

How It Works

  1. Delimiters are ignored. findInLine("#\\d+") skips past "Order " and matches "#402" directly.
  2. Cursor stops right after match. The second search begins at " shipped..." and grabs "19.50" while leaving " today" unread.
  3. Remainder still intact. Calling nextLine() reads " today" after the second match.

Example 2 — See Why findInLine() Returns null Before a Line Break

Search for a token on line 2 before and after calling nextLine() to cross the newline.

Java
import java.util.Scanner;

public class ScannerFindInLineBoundary {
    public static void main(String[] args) {
        String log = "Row1: alpha\nRow2: beta";
        try (Scanner sc = new Scanner(log)) {
            System.out.println("Line 1 search for beta: " + sc.findInLine("beta"));
            System.out.println("Skipped line 1: [" + sc.nextLine() + "]");
            System.out.println("Line 2 search for beta: " + sc.findInLine("beta"));
        }
    }
}

How It Works

  1. Search stops at newline. On line 1, "beta" lies after \n, so findInLine("beta") returns null.
  2. Cursor did not move. Calling nextLine() right after still prints the full first line Row1: alpha.
  3. Line 2 match succeeds. Once past \n, findInLine("beta") locates and returns "beta".

Example 3 — Extract Key=Value Pairs on One Line with Pattern and match()

Combine a compiled Pattern with findInLine() in a loop and pull out capture groups via sc.match().

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

public class ScannerFindInLineGroups {
    public static void main(String[] args) {
        Pattern kv = Pattern.compile("(\\w+)=(\\d+)");
        String line = "width=800, height=600, depth=32";
        try (Scanner sc = new Scanner(line)) {
            while (sc.findInLine(kv) != null) {
                MatchResult m = sc.match();
                System.out.println(m.group(1) + " -> " + m.group(2));
            }
        }
    }
}

How It Works

  1. Compiled regex with capture groups. (\\w+)=(\\d+) captures the key in group 1 and the integer in group 2.
  2. Loop until null. Each non-null result advances past one pair, ignoring commas and spaces around it.
  3. Read groups from MatchResult. Calling sc.match() retrieves each pair cleanly without splitting the string manually.

Frequently Asked Questions

No. It searches only from the current position up to the next line separator. Use findWithinHorizon(pattern, 0) to search across multiple lines.
It returns null and leaves the scanner cursor at its previous position.
No. Both findInLine() and findWithinHorizon() ignore the scanner delimiter pattern.
Call sc.match() immediately after a non-null result and read m.group(1), m.group(2), etc.
It throws PatternSyntaxException at run time.

Next: findWithinHorizon()

Search across lines up to a character horizon for a regex match.

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

9 people found this page helpful