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


Pattern represents a regular expression.

Simple Example

A Pattern object represents one regular expression. A Pattern object is created by the static compile(String regExp) method of the Pattern class. The method's parameter is a string containing a regular expression in text form.

A Matcher object links a Pattern object with a string of characters. It has several methods that perform matching between the pattern and the string.

The Matcher object is created by the matcher(String target) method of a Pattern object. Its parameter is the target string that is to be matched.

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

public class SimpleMatch
  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( "xxxxxxyyyy" );    
    // match the regular expression with the target string
    if (matcher.matches())                               
      System.out.println( "Match" );     
      System.out.println( "No Match" );

This simple program prints out "Match" because the regular expression x+y+ matches the entire target string "xxxxxxyyyy".


Wouldn't it be easier just to use the matches() method of String ?

if ( "xxxxxxyyyy".matches( "x+y+" ) )