Learn

Character classes are one of the primary means of “grouping” characters in a regex pattern without necessarily enforcing an order to those characters. For instance, a character class marks the difference between searching for a specific word and searching for any occurrence of any letters found in that word.

A *character class matches a character from a specific set, including predefined character classes and custom user-defined sets. The following are examples of how character classes are used (note that any references to “abc” are just examples. These are user-defined, so anything can be used):

Character Class Description
[abc] Includes any of the contained characters
[^abc] Excludes all of the contained characters
[a-z] Includes any of the contained characters across a range
. Any character except newline
\w Any word character (alphanumeric and underscore)
\d Any digit [0-9]
\s Whitespace (spaces, tabs, line breaks)

These can all be defined as or included in a regex search pattern. Let’s go over a quick example using a character class. Suppose the following is your search pattern:

Pattern pattern = Pattern.compile("[A-Z]\w+");

The above pattern first creates a character class that grabs any capital letters:

“[A-Z]”

Then from each capital letter found, we then also grab one or more word characters in front of those capital letters until a whitespace is found.

“\w+”

Don’t worry about the + for now, we’ll cover what that is later! For now, just know that this essentially grabs any full words that start with a capital letter. If a capital letter is found in the middle of a word, it will grab the latter portion of that word starting from the capital letter.

Instructions

1.

Declare and compile a pattern called pattern, using a character class, that can match both the American and British English spellings for the word “gray”.

2.

Declare your matcher, call it matcher, and use the pattern object’s matcher() method with the following text to match against:

"Vibrant light bloomed across the gray sky, illuminating its grey haze in flashes amidst rolling hills of wispy gray clouds. Colors of gold, pink, and purple painted the horizon, the dull grey of the sky overtaken by brief moments of a quiet twilight storm."

Let’s count how many instances of "gray" and "grey" exist in the above text.

Using your matcher object, call find() and use a while loop to keep track of a count integer. Store the result of the count and print it.

3.

For consistency, let’s go ahead and use the matcher method replaceAll() again. We’ll use the arbitrary string "gray" as the text to replace all matches.

Store the results of the replace in a string and print it.

Run your code and view the results.

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?