Regular Expression Processing

In this chapter you will learn:

  1. What are the classes we use to do Regular Expression Processing
  2. What is Pattern class for
  3. What is Matcher class for

Classes for Regular Expression Processing

A regular expression is a pattern. And we use the pattern to find matches in other strings.

There are two classes that support regular expression processing: Pattern and Matcher.

Pattern define a regular expression. Matcher do the matching with the pattern.

Pattern class

The Pattern class defines no constructors. A pattern is created by calling the compile() factory method.

One of its forms is shown here:

static Pattern compile(String pattern)

pattern parameter is the regular expression.

Matcher class

Matcher is created by calling the matcher() factory method defined by Pattern. It is shown here:

Matcher matcher(CharSequence str)

str is the character sequence that the pattern will be matched against.

CharSequence is an interface that defines a read-only set of characters. It is implemented by the String class. You can pass a string to matcher().

Once you have created a Matcher, you will use its methods to do various pattern matching operations.

Matcher defines the following methods:

  • boolean matches()
    determines whether the character sequence matches the pattern. It returns true if the sequence and the pattern match, and false otherwise.
  • boolean find()
    To determine if a subsequence of the input sequence matches the pattern. It returns true if there is a matching subsequence and false otherwise. This method can be called repeatedly to find all matching subsequences.
  • String group()
    returns a string containing the last matching sequence by calling group().
  • int start()
    returns the index within the input sequence of the current match
  • int end()
    return the index past the end of the current match.
  • String replaceAll(String newStr)
    replace all occurrences of a matching sequence with another sequence. The updated input sequence is returned as a string.

Next chapter...

What you will learn in the next chapter:

  1. What are the four type of characters in regular expressions
  2. How to use Normal character in regular expressions
  3. A match with a literal pattern
Home » Java Tutorial » Regular Expressions
Regular Expression Processing
Normal characters
Character class
Wildcard Character
Quantifier
Wildcards and Quantifiers
Character class and quantifiers
Find sub string
Multiple subsequences
Replace all
Split