(...)
Capturing group.
Groups capture parts of a match. Quantifiers control how many times a pattern may repeat.
const pattern = /^(?<year>\d{4})-(?<month>\d{2})$/;
const match = "2026-06".match(pattern);
console.log(match?.groups?.year);
Regular Expressions
Parentheses create groups. Capturing groups save parts of the match so code can read them later.
Named groups make extraction much clearer than relying only on numeric positions. Non-capturing groups use (?:...) when you need grouping but not extraction.
Quantifiers such as *, +, ?, {2} and {2,4} control repetition. Use them carefully to avoid matching too much.
Capturing group.
Named capturing group.
Non-capturing group.
Quantifiers that control repetition.
Examples
const pattern = /^(?<name>[a-z]+):(?<value>\d+)$/i; const match = "score:42".match(pattern); console.log(match?.groups?.value);
const match = "score:42".match(/^([a-z]+):(\d+)$/i); console.log(match[2]); // Which group is match[2] again?
Code patterns
These examples are intentionally small. Regex becomes useful when each pattern has one clear job and a readable method around it.
Extract data by name.
const pattern = /^(?<year>\d{4})-(?<month>\d{2})$/;
const match = "2026-06".match(pattern);
console.log(match.groups.year);
Group choices without storing them.
const pattern = /^(?:draft|ready|archived)$/;
+ requires at least one match.
const pattern = /^\d+$/;
? makes a section optional.
const pattern = /^color-#[0-9a-f]{6}$/i;
Rules that matter
Regular expressions are compact by design. Good JavaScript around the pattern is what makes them safe to maintain.
Names make matches self-documenting.
Do not capture values you will not use.
* allows zero, + requires at least one.
Greedy quantifiers can consume more than expected.
? can make invalid input look valid.
A matched string is not always a safe value.
Production thinking
Groups turn regex from yes/no matching into structured extraction.
Extracted labels or values should be checked before they are shown to users.
Production extraction patterns should use named groups and cover invalid input in tests.
Regex extraction can help normalize slugs or metadata, but output should remain predictable.
Live code lab
The preview runs inside an isolated iframe. The JavaScript is placed inside the HTML editor for now, so every example stays together and remains easy to understand.
Mini assignment
Practice assignment
Try it yourself
Self-check
Regex skill is not memorizing every token. It is knowing how to build small patterns and choose the right string method around them.