Java Scanner search for specified pattern within next line of text

Introduction

To search for the specified pattern within the next line of text, use findInLine() method.

Its general forms are shown here:

String findInLine(Pattern pattern )  
String findInLine(String pattern ) 

If the pattern is found, the matching token is consumed and returned.

Otherwise, null is returned.

Full source


// Demonstrate findInLine(). 
import java.util.Scanner;

public class Main {
  public static void main(String args[]) {
    String instr = "Name: demo2s.com Age: 2 ID: 001";

    Scanner conin = new Scanner(instr);

    // Find and display age.
    conin.findInLine("Age:"); // find Age

    if (conin.hasNext())
      System.out.println(conin.next());
    else//from   w w  w. j ava2s . c om
      System.out.println("Error!");

    conin.close();
  }
}



PreviousNext

Related