Scanner finding

In this chapter you will learn:

  1. How to let Scanner to find within next line
  2. How to let Scanner to find within a distance

Find within next line

findInLine( ) is useful if you want to locate a specific pattern. This method searches for the specified pattern within the next line of text. If the pattern is found, the matching token is consumed and returned. Otherwise, null is returned.

Its general forms are shown here:

String findInLine(Pattern pattern) 
String findInLine(String pattern)
import java.util.Scanner;
/* java 2 s.c o m*/
public class MainClass {
  public static void main(String args[]) {
    String instr = "Name: Joe Age: 28 ID: 77";

    Scanner conin = new Scanner(instr);

    conin.findInLine("Age:"); // find Age

    if (conin.hasNext())
      System.out.println(conin.next());
    else
      System.out.println("Error!");

  }
}

The code above generates the following result.

Find within a distance

String findWithinHorizon(Pattern pattern, int count) 
String findWithinHorizon(String pattern, int count)

findWithinHorizon() attempts to find an occurrence of the specified pattern within the next count characters. If successful, it returns the matching pattern. Otherwise, it returns null. If count is zero, then all input is searched until either a match is found or the end of input is encountered.

import java.util.Scanner;
//from j a v a 2  s.c o  m
public class Main {
  public static void main(String args[]) {
    Scanner sc = new Scanner("Name: Tom Age: 28 ID: 77");

    sc.findWithinHorizon("ID:",100);

    if (sc.hasNext())
      System.out.println(sc.next());
    else
      System.out.println("Error!");
  }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. What is URL
  2. How to get a connection from URL
Home » Java Tutorial » I/O
RandomAccessFile
FilenameFilter
StreamTokenizer
Console
Console password reading
Scanner creation
Scanner read and scan
Scanner Delimiters
Scanner finding