Back to roadmaps regex Course

Capturing Groups: Extracting Matched Substrings

Parentheses () in regex serve two purposes: they group part of a pattern together, and they capture the matched text for later use.


1. Basic Capturing Groups

When you use match() or exec(), each group is returned as a separate item in the result array:

const logLine = "2026-06-16 14:35:00 ERROR Server timeout";

// Capture the date, time, and log level as separate groups
const match = logLine.match(/^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2}) (\w+)/);

if (match) {
  console.log(match[1]); // "2026-06-16" (group 1: date)
  console.log(match[2]); // "14:35:00" (group 2: time)
  console.log(match[3]); // "ERROR" (group 3: level)
}

2. Named Capturing Groups

Use (?<name>...) syntax to give each captured group a human-readable name:

const regex = /^(?<date>\d{4}-\d{2}-\d{2}) (?<level>\w+)/;
const match = "2026-06-16 ERROR message".match(regex);

if (match) {
  console.log(match.groups.date);  // "2026-06-16"
  console.log(match.groups.level); // "ERROR"
}

3. Non-Capturing Groups

If you need to group elements for quantifier or alternation purposes without capturing the result, use (?:...):

// Group "https://" or "http://" for the ? quantifier without capturing
const urlRegex = /^(?:https?):\/\/[\w.-]+/;
urlRegex.test("https://example.com"); // true
urlRegex.test("http://example.com");  // true
Published on Last updated: