Introduction to the Pattern and Matcher Classes



There are two classes that are used with regular expressions: Pattern and Matcher. Let's go over each one. 

A Pattern object represents a compiled version of a regular expression; in other words, it turns a regular expression String into a "pattern", which can be compared with a "normal" String. There are three very important methods in the Pattern class:
  • compile (String regex) - returns a Pattern from the regular expression string
  • matcher(String text) - returns a Matcher instance that can compare the text with the regular expression multiple times
  • matches(String text, String regex) - returns a boolean; compares a regular expression with a text string only one time (returns true if they match, false if they don't)
A Matcher object compares the "pattern" made from the regular expression with text multiple times. It allows you to find multiple occurrences of a phrase within text. The Matcher class has several important methods.
  • matches() - returns a boolean; compares a regular expression with the entire text string
  • lookingAt() - returns a boolean; compares a regular expression with only the beginning of the string. 
  • find() - returns a boolean; tries to find the next occurrence of a "pattern" in the text processed by the matcher method in the Pattern class. Once one "pattern" is found and the method is called again, the find() method analyzes the text after the expression that had just been found. This method is often used in while loops, which we will go over in the next lesson.
  • start() - returns an integer; returns the index of the first character in the "pattern" found in the text for each time the find() method runs.
  • end() - returns an integer; returns the integer after the index of of the first character in the "pattern" found in the text for each time the find() method runs.
Some of this might be confusing right now, but seeing these classes in action in the next lesson should help out.