Alternation is just the regex way of saying OR. In regex, this is denoted by the following (note the “ab” and “cd” are user-defined):
The use of alternation works exactly as you’d expect the boolean OR to work. The pattern will search for any text that matches either alternated pattern and only return nothing if neither is found. Otherwise, this pattern will group either match together in the search results regardless of which pattern matched.
Alternation is also found, implicitly, in character classes. For instance, a character class like
[A-Z] grabs a range of characters, but it intuitively understands that it can grab any
C and so on to gather its search results.
This just allows you to get a bit more complicated, especially if you want to look for slight differences between words that generally share a pattern. For instance, when looking at code, someone might type the following in two possible ways:
i < 10 10 > i
Both ways are technically correct and produce the same result. So to make a regex pattern accept both when looking for the same technical thing, you can write a pattern for each and just alternate it with an
| to ensure you’re finding both feasible ways to write the same code.
We’ve written a pattern in these exercises that searches for both versions of the word
"gray". Let’s approach this problem again but from the standpoint of using alternation.
Declare a pattern called
pattern that uses alternation to find all instances of
"grey" in a given text. Declare the same matcher object you did before, call it
matcher, with the following text to match:
"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."
find() and a
while loop to print the result and check your work. Additionally, use
replaceAll() to replace all occurrences with the word
"grey" this time. Print the result of the replacement.
Run your code.