To grasp the use case of
y flag, and see how great it is, let’s explore a practical use case.
One of common tasks for regexps is “parsing”: when we get a text and analyze it for logical components, build a structure.
Writing parsers is a special area, with its own tools and algorithms, so we don’t go deep in there, but there’s a very common question: “What is the text at the given position?”.
For instance, for a programming language variants can be like:
- Is it a “name”
- Or is it a number
- Or an operator
- (a syntax error if it’s not anything in the expected list)
regexp.lastIndex property, but that’s not we need!
We’d like to check the match exactly at given position, not “starting” from it.
Here’s a (failing) attempt to use
The match is found, because
regexp.exec starts to search from the given position and goes on by the text, successfully matching “function” later.
We could work around that by checking if "
regexp.exec(str).index property is
5, and if not, ignore the much. But the main problem here is performance.
The regexp engine does a lot of unnecessary work by scanning at further positions. The delays are clearly noticeable if the text is long, because there are many such searches in a parser.
So we’ve came to the problem: how to search for a match, starting exactly at the given position.
y flag does. It makes the regexp search only at the
Here’s an example
As we can see, now the regexp is only matched at the given position.
y does is truly unique, and very important for writing parsers.
y flag allows to apply a regular expression (or many of them one-by-one) exactly at the given position and when we understand what’s there, we can move on – step by step examining the text.
Without the flag the regexp engine always searches till the end of the text, that takes time, especially if the text is large. So our parser would be very slow. The
y flag is exactly the right thing here.