Lesson 66 - Grouping & Capturing in Regular Expressions
Regular expressions allow us to group parts of a pattern using parentheses (...)
.
This is useful when we need to capture specific parts of a string for further processing.
Grouping in Regular Expressions
Grouping is mainly used for repeating multiple characters together and capturing substrings.
Example 1: Using Groups for Repetition
let regex = /(ha)+/;
console.log("hahaha".match(regex)); // Output: ["hahaha"]
Here, (ha)+
means "repeat the ha sequence at least once."
Capturing Groups
Capturing groups store the matched parts so you can access them later.
Example 2: Extracting Parts of a String
let regex = /My name is (\w+)/;
let result = "My name is John".match(regex);
console.log(result[1]); // Output: "John"
The parentheses capture the name, allowing us to extract "John"
from the string.
Non-Capturing Groups
If you don’t want to store the match, use (?:...)
.
let regex = /(?:ha)+/;
console.log("hahaha".match(regex)); // Output: ["hahaha"]
Unlike regular groups, this does not store "ha"
separately.
Using Groups with replace()
Captured groups are useful when modifying text.
let regex = /(\w+)@(\w+).com/;
let str = "Email: test@example.com";
let replaced = str.replace(regex, "[$1 at $2]");
console.log(replaced); // Output: "Email: [test at example]"
Try Your Hand ?
- Write a regex to match a date format like
12-05-2025
and extract day, month, and year. - Modify a string like
"Hello John, meet Sarah"
to"Hello, John! Meet, Sarah!"
using regex groups.