go to previous page   go to home page   go to next page



find() Method

The find() method tries to match a substring of the string with the Pattern. It is OK if the start and the tail of the string do not match. find() returns true if it found a match (and false, otherwise). The substring that matched is available using the group() methods.

Here is a program that shows this:

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class SimpleFind
  public static void main(String[] args)
    // create a Pattern object for a regular expression
    Pattern pattern = Pattern.compile( "x+y+" );    
    // create a Matcher object for a target string     
    Matcher matcher = pattern.matcher( "BBBB  AAAAAA  xxxxxxyyyy AAAAAAA BBBBB" );    
    // match the regular expression with the target string
    if (matcher.find())                               
      System.out.println( "I found: " + matcher.group(0));     
      System.out.println( "No Match" );

This simple program prints out "I found: xxxxxxyyyy" because the regular expression x+y+ is found within the target string.


Might the same regular expression be found in several locations in a string?

For example, consider x+y+ and the string "AAA xxyy BBB xxxy CCC"