Java’s java.util.regex package contains three vital classes:

  • Pattern Class
  • Matcher Class
  • PatternSyntaxException Class

We’ll start with the Pattern class. This class is Java’s way to define regex search patterns. It does so through the following method:

Pattern pattern = Pattern.compile("Codecademy"); Pattern pattern = Pattern.compile("codecademy", Pattern.CASE_INSENSITIVE);

This method compiles a pattern object in such a way to designate a given string as the pattern to be used to perform regex operations, which makes this method the first half of your bread and butter of regex in Java. Consider this your bread.

Note the second parameter. It’s optional but contains some useful flags you can set that affect how the regex search is performed. Some examples include:

  • Pattern.CASE_INSENSITIVE - The case of letters will be ignored when performing a search.
  • Pattern.LITERAL - Special characters in the pattern will not have any special meaning and will be treated as ordinary characters when performing a search.
  • Pattern.UNICODE_CASE - Use it together with the CASE_INSENSITIVE flag to also ignore the case of letters outside of the English alphabet.

Next is the second half of our metaphor. Your butter is represented by the following method:

Matcher matcher = pattern.matcher("Welcome to Codecademy!");

This is your first glimpse of the Matcher class, but note that the Pattern object is called when using the matcher() method. The matcher() method is what performs the “search,” returning a Matcher object which contains information about the search based on the pattern compiled into the Pattern object being used.

In order to bridge this relationship between these two classes, let’s talk about the Matcher class next!


The Pattern class can’t do much without the Matcher class, so let’s talk about that next!

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?