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

Answer:

Yes.


Creating a Pattern object

Create a Pattern object using a factory method, compile() of the Pattern class. This is a static method, so you invoke it using the class, not an object:

Pattern pat = Pattern.compile( "x+y+");

A factory method (such as compile()) is a static method of a class that creates an object. It is like a constructor, but is not used with the new operator. It has a name other than the class name. Here are the two ways to call compile():

public static Pattern compile(String regex)
Creates a Pattern object based on the regular expression in regex. It throws a PatternSyntaxException if the expression's syntax is invalid.
public static Pattern compile(String regex, int flags)
Creates a Pattern object based on the regular expression in regex. Various options are chosen by setting various bits in flags. It throws a PatternSyntaxException if the expression's syntax is invalid. It throws a IllegalArgumentException if flags is invalid.

Details about the flags and the exceptions are discussed below. For now, assume that the program will halt (and produce a stack trace) if the expression or the flags are incorrect.


QUESTION 4:

Does the following look correct?

Pattern pets = Pattern.compile( "ant|bat|cat|dog" );