Let us 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
- Then we add
|
- Then we enter the second option
We can see this match:
/gray|grow
/
gray
grow
grey
We can write the same condition more shortly. Since these substrings have a common part, we enter gr
characters and then add an alternative using grouping:
/gr(ay|ow)
/
gray
grow
grey
Grouping is really 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. We spell this word gray
in American English but grey
in British English. 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 us 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, which job is to match things, works much more efficiently with character classes, especially single classes.
Are there any more questions? Ask them in the Discussion section.
The Hexlet support team or other students will answer you.
For full access to the course you need a professional subscription.
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.