Capturing Groups
A capturing group is part of a regular expression that is enclosed in parentheses. Capturing groups allow you to extract portions of a string that match a specific part of the pattern.
When a regular expression matches a string, the matching portions are grouped and stored. These groups can then be accessed later for further use, like extracting values or applying operations.
When you define a capturing group using parentheses (), you’re essentially telling the regular expression engine: “I want to remember this specific part of the match”.
Consider this regular expression:
const mulRegex = /mul\((\d{1,3}),(\d{1,3})\)/;
The start and end of a regular expression is signaled by the forward slash /.
The forward slash is followed by the literal string “mul”.
Because parentheses are reserved for capturing groups. Signaling a literal parentheses character requires you to escape it using a backslash.
Then the first capture group follows it. \d signals any digit, meaning 0-9. {1,3}
specifies that the previous element (a digit 0-9) must occur between 1 and 3 times.
When calling .matchAll()
on a source string, it is possible to loop over all found matches using a for … of loop. Then, when we call .match()
on every match, an array will be produced where the first element will be the entire match itself. Subsequent elements are the values of the capturing groups in the regex. We can then use destructuring syntax to reuse these capturing group values as variables like so:
const [, x, y] = fullMatch.match(mulRegex);
Note that the comma is used to represent skipping a value in destructuring.