Creating Pattern and Match Objects

Introduction

Pattern and Match classes are integral parts of regular expressions in Java. As defined by Oracle, a Pattern is a ‘compiled representation of regular expression.’ Also defined by Oracle, the Matcher class is ‘an engine that performs match operations on a character sequence by interpreting a Pattern.’ Both the Pattern and the Matcher classes are part of the java.util.regex package. Therefore, you will need to import the package to create objects. In this article, we will see how to create objects of the Pattern and the Matcher classes.

Pattern Object

Signature: public final class Pattern extends Object implements Serializable

After you create a regular expression, you will first need to compile it into an instance of the Pattern class. Only then can the matcher match it with a third-string or a sequence of characters.

Object of Pattern class: Pattern pat = Pattern.compile (“.*?[0-9]{10}.*”);

Matcher Object

Signature: public final class Matcher extends Object implements MatchResult

A matcher is always preceded by a pattern. The matcher engine takes in the pattern and uses it as a reference to further check for similarities to inputted sequences of characters or strings.

Object of Matcher Class: Matcher m = pat.matcher(str);
//The matcher method is called on the pattern object always

A matcher object can be used to carry out three different operations. The most commonly used method is the matcher() as mentioned above. It is used to find matches between a pattern and an arbitrary string. The lookingAt() method aims to match the input string, starting at the beginning, with the given pattern. The find() method acts as a scanner. It scans the input sequence to find matches in the latter parts of the string that matches the pattern.

Example

A typical sequence of pattern and match objects put to use is as follows:

Pattern p = Pattern.compile(“a*b”);
Matcher m = p.matcher(“aaaaab”);
boolean b = m.matches();

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.