Sticky Mode (y) in Regular Expressions
1. What is Sticky Mode?
Sticky mode, denoted by the y
flag, is a feature in regular expressions that ensures the pattern match starts exactly at the specified position in the string. Unlike global search (g
), which finds all matches regardless of position, sticky mode requires the match to begin at the current index set by the lastIndex
property.
2. How Sticky Mode Works
When the y
flag is used, the regular expression engine will only attempt to match the pattern starting from the position specified by lastIndex
. If a match is not found at that exact position, the engine will not search further in the string.
Example:
Pattern: /foo/y
with lastIndex
set to 3
Text: "barfoobar"
Matches: "foo" starting at index 3
Explanation: The pattern matches "foo" only if it starts at index 3. Since "foo" starts at index 3, it matches.
3. Setting the lastIndex Property
The lastIndex
property is crucial in sticky mode. It specifies the position in the string where the next match should begin. If the match does not start at this position, it will fail, even if the pattern exists elsewhere in the string.
Example:
Pattern: /bar/y
with lastIndex
set to 0
Text: "barfoobar"
Matches: "bar" starting at index 0
Explanation: The pattern matches "bar" only if it starts at index 0. Since "bar" starts at index 0, it matches.
4. Practical Use Cases
Sticky mode is particularly useful in scenarios where you need to ensure that a pattern match starts at a specific position in the string. This can be helpful in text parsing, tokenization, and other applications where the position of the match is critical.
Example:
Pattern: /[a-z]+/y
with lastIndex
set to 5
Text: "12345abc6789"
Matches: "abc" starting at index 5
Explanation: The pattern matches a sequence of lowercase letters starting at index 5. Since "abc" starts at index 5, it matches.
5. Combining Sticky Mode with Other Flags
Sticky mode can be combined with other flags to create more complex patterns. For example, combining it with the case-insensitive flag (i
) allows for case-insensitive matches starting at a specific position.
Example:
Pattern: /hello/yi
with lastIndex
set to 0
Text: "HelloWorld"
Matches: "Hello" starting at index 0
Explanation: The pattern matches "hello" in a case-insensitive manner starting at index 0. Since "Hello" starts at index 0, it matches.
6. Real-World Application
In real-world applications, sticky mode is often used in text processing tasks where the position of the match is crucial. For example, in a text editor, sticky mode can be used to highlight specific patterns starting at a cursor position.
Example:
Pattern: /[0-9]+/y
with lastIndex
set to cursor position
Text: "Price: 100 USD"
Matches: "100" starting at cursor position
Explanation: The pattern matches a sequence of digits starting at the cursor position. This can be used to highlight or extract numbers at specific positions in the text.