JS RegExp Patterns

JavaScript RegExp Patterns: Groups and Ranges

If you need to match specific letters, numbers, or a sequence of characters, Regular Expressions use Brackets to define character ranges, and Parentheses to create groups.


1. Brackets for Ranges [...]

Square brackets [] are used to find a range of characters. Any character placed inside the brackets is an acceptable match.

Expression Description
[abc] Finds any character between the brackets (a, b, or c).
[^abc] Finds any character NOT between the brackets.
[0-9] Finds any digit from 0 to 9.
[a-z] Finds any lowercase letter from a to z.
[A-z] Finds any letter, uppercase or lowercase.

Brackets Example: Finding Vowels

let text = "JavaScript is awesome!";

// Find every vowel in the string let vowels = text.match(/[aeiou]/gi);

console.log(vowels); // ["a", "a", "i", "i", "a", "e", "o", "e"]


2. Parentheses for Grouping (...)

Parentheses () are used to group parts of a pattern together. This allows you to apply quantifiers (like + or *) to an entire group of characters rather than just a single character.

Grouping Example

let text = "ha haha hahaha hah";

// Match the group "ha" repeated one or more times let result = text.match(/(ha)+/g);

console.log(result); // ["ha", "haha", "hahaha", "ha"]


3. Capturing Groups

When you place parentheses around a pattern, the RegExp engine automatically captures whatever matches inside those parentheses. You can then extract those specific captured pieces from a string!

This is widely used to extract data from strings, like pulling the domain name out of an email address.

Capturing Group Example

let email = "user@intricatedevo.com";

// We capture the username (Group 1) and the domain (Group 2) let regex = /([^@]+)@([^@]+)/;

let match = email.match(regex);

// match[0] is the full match ("user@intricatedevo.com") // match[1] is the first captured group // match[2] is the second captured group

console.log("Username: " + match[1]); // "user" console.log("Domain: " + match[2]); // "intricatedevo.com"

Non-Capturing Groups (?:)

If you want to group characters together (for logic or quantifiers) but you do not want the engine to save the result in memory as a capture, use (?:...). This saves performance!


Exercise

?

Which syntax would you use to match any character that is NOT a lowercase vowel?