The butter to our bread is the
Matcher class. This is Java’s “search” feature, allowing it to take a regular expression defined by the
Pattern class and perform a search based on a compiled pattern.
As you saw before, the
matcher() method used by a
Pattern object returns a
Matcher object with information about the search. We can then use this new
Matcher object to sift through that information in varying ways, with many methods within the
Matcher class at your disposal. We’ll start by talking about the two most useful and basic methods:
boolean matchNext = matcher.find(); boolean matchAny = matcher.matches();
In the above two methods,
find() finds the next match based on the pattern used in the search and returns a boolean if it finds it. If no instances exist anywhere in the text being searched, then if this returns true on its first running it indicates no matches exist anywhere within the text.
This is functionally the same as
matches() which does exactly that. It finds any match anywhere inside the text, regardless of how many exist, and returns a boolean if it finds one. This is good to use if you’re looking for a “catch-all” case of “does it exist anywhere?” and only care about the first occurrence.
find() can be useful if you’re looking for a certain amount of occurrences, or trying to count occurrences as you go.
Matcher methods also include ways to find and replace text, create search regions, append text, display how the matcher is interpreting the pattern, and many more functional and very useful utilities.
For now, this is all we’ll need to start delving into writing and understanding search patterns in regex. Let’s get to talking about those next!
PatternSyntaxException is thrown to indicate a syntax error in a regular expression pattern. That’s all the
PatternSyntaxException class is really used for.
We’ll cover more complex patterns later in the lesson, but we can start with a simple setup for this checkpoint.
Declare a pattern called
pattern and compile it with
"nap time". Make it
Declare a matcher called
matcher and call the pattern object’s
matcher() method using
"Every morning starts with some nap time!".
Now, let’s do something with our regex results! We’ve stored some information in our matcher object pertaining to how regex applied our compiled pattern to the text being searched.
Let’s use the regex text replace method.
Using the matcher object, call the
replaceAll() method and give it the parameter
"Codecademy". This method returns the full text as a string after the replacement occurs, so store that result into a string variable.
Any matches found during the search will be replaced with the text given by the parameter. Now let’s see what the new text looks like.
Add one final line of code to print your result string.
Run your code and see the results!