Let's see how we can use regular expressions to find similar character combinations.
If we want to find the substrings gray
or grow
in the string, we need to use a mechanism called “alternation”: we enter the first possible option, followed by a “|”, followed by the second option. We can see the following match:
/gray|grow
/
gray
grow
grey
The same condition can be written in an even shorter way. Since these substrings have a common part, let's enter gr
characters and then, using grouping, add an alternative:
/gr(ay|ow)
/
gray
grow
grey
Grouping is very important here. If we remove it, the alternative to gray
becomes ow
:
/gray|ow
/
gray
grow
grey
Below is another interesting example of using alternation. While it's spelt gray
in American English, in British English it's grey
In order to avoid missing any of the options in the text, we can use a concise alternative:
/gr(a|e)y
/
gray
grow grey
And we can simplify the resulting expression, since the alternative uses single characters. Let's specify a character class that consists of the characters a
and e
:
/gr[ae]y
/
gray
grow grey
In this case, the regular expression mechanism, whose job is to match things, works much more efficiently with character classes, especially single classes.
The Hexlet support team or other students will answer you.
A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.
Programming courses for beginners and experienced developers. Start training for free
Our graduates work in companies:
From a novice to a developer. Get a job or your money back!
Sign up or sign in
Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.