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

Answer:

Yes.


lookingAt Capture Groups

The substrings matched by capture groups of the regular expression are kept in the Matcher object. They can be retrieved using the group(int) method. This works after a successful match with the matches(), lookingAt(), or find() method.

Here is the example program modified to show this:

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

public class SimpleLooking
{
  
  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 AAAAAAA BBBBB" );    
    
    // match the regular expression with the target string
    if (matcher.lookingAt())                               
      System.out.println( "Looking At: " + matcher.group(0) );     
    else
      System.out.println( "No Match" );
  }
}

Remember that group(0) is the entire part of the string that was matched. This is true even if there are no explicit capture groups in the regular expression.


QUESTION 15:

Would it be useful in the above to match a pattern somewhere within a string?