+ character used in the character class example? That’s what regex calls a quantifier.
Quantifiers look at preceding tokens and indicate how many matches to look for, defaulting to trying to match as many characters as possible unless otherwise defined. The following are examples of quantifiers (note that “a” is user-defined and can be any character or group of characters. Any numerical digits used are also user-defined):
||0 or more|
||1 or more|
||0 or 1|
||Three or more|
||Between one and three|
||Match as few as possible|
||Match as few as possible with a lower bound|
Patterns with quantifiers are generally straightforward. All they do is grab and group the quantified amount of characters together when found. Let’s cover a quick example:
Pattern pattern = Pattern.compile("a*b");
This pattern searches for text that includes 0 or more “a”s followed by a “b.” It’ll find any “ab,” “aab,” “aaaaaaab,” but also, because it can match any text that has 0 “a”s followed by a “b,” it will also find “b.”
Let’s see if we can find all words with at least 2 instances of the letter
This is a more complicated pattern, so let’s write it in stages. First, declare a pattern called
pattern that finds all instances of the letter
Now, declare a matcher called
matcher with the text to search set to
"Is it Bananagrams or Banana Grams?" and count the occurrences with
find() and a
Print the resulting
You can manually count the
as in the string and check your work that way. You can also check the hint for the correct number.
We need a way to start at the first
a and then find a second
a somewhere within the same word without knowing if there will be any characters between the
as or how many there might be.
You’ll need to use a combination of a quantifier and a predefined character class to do this.
Modify your pattern to return any results that fit these criteria.
Note: Right now, we don’t care about finding the end of the word. We just want instances of any text that contains a sequence of 2
as. This one’s tricky! So don’t be afraid to check out the hint!
Let’s grab the full words now.
This can be done by utilizing the same method you did in the previous step, but applying it to the start and end of the pattern.
Modify the pattern to match the full word meeting the criteria described in these instructions.
replaceAll() with any string parameter you’d like to replace the found words. Print the result of the replacement.
Run your code.