Let's look at what are called flags, which allow you to change the behavior of regular expressions and the rules for searching for matches in a string.
Look at this example:
/aa
/
aa
aa aa
The regular expression aa
for some reason corresponds to only one substring in this line, although we can see that there should be three. This happens because by default, regular expressions only look for the first match. Flags are used to change their behavior.
If you've already used the regular expression editor during this course, or just watched the course video, you'll have noticed the box to the right of the pattern string. The most common flag in it is the /g
flag, which is called global
. It includes a search for all matches in the string, and doesn't stop after the first match. Let's set a g
flag. Now all the substrings are matched:
/aa
/g
aa aa aa
In this course, we've used the g
flag by default in our examples, and we haven't actually added it to anything, but you may see it in regular expressions in tests and practical exercises, so if you see /g
at the end of a regular expression, you'll know that it's the global search flag.
NB! The global flag is often used when you want to not only find a match for a regular expression in a string, but also retrieve or otherwise use the search results.
Depending on the programming language, flags can be included directly in the regular expressions themselves, or they can be set in other ways. If you want to see how this is implemented in a given language, you should check that language's documentation.
Finally, let's look at a few more flags.
- the
/i
flag turns on case-insensitive mode:
/aa
/gi
aa Aa AA
- the
/s
flag makes.
mean a line break. It makes it so that the string that the matches are being searched for in able to be presented as a single line. This can come in handy at times.
Do the flags remind you of something we've looked at before? If they do, that's because they're essentially more powerful versions of the modifiers we covered in Lesson 8. The modifiers allow you to make more point-by-point changes to the matching rules, while flags do it on a global level.
There are several other flags. Studying the rest of them is your assignment after this lesson. Go into any regular expression editor, read the documentation on flags, play around with the examples they give, and be sure to try using each flag.
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.