Lab 11: Regular Expressions

Objective

Master JavaScript regular expressions — create patterns, use flags, extract groups, search and replace text, and apply regex to real-world tasks like validation, log parsing, and data extraction.

Background

Regular expressions (regex) are a pattern-matching language built into JavaScript. They power form validation, log analysis, search-and-replace in editors, URL routing, and data parsing. A single regex pattern can replace 20 lines of string-splitting code. Learning regex is one of the highest-leverage skills in any language.

Time

45 minutes

Prerequisites

  • Lab 03 (Functions & Scope)

  • Lab 04 (Arrays & Objects)

Tools

  • Node.js 20 LTS

  • Docker image: innozverse-js:latest


Lab Instructions

Step 1: Creating Patterns — Literals and Constructors

Two ways to create regex in JavaScript: literal syntax /pattern/flags and new RegExp().

💡 Flags matter: i = case-insensitive, g = global (find all), m = multiline, s = dotAll (. matches newlines). Without g, .match() returns only the first result.

📸 Verified Output:


Step 2: Character Classes and Quantifiers

Build patterns using character classes [], anchors ^$, and quantifiers +*?{}.

💡 \d = [0-9], \w = [a-zA-Z0-9_], \s = whitespace, \D/\W/\S = their negations. The ^ inside [] negates the class; outside it anchors to string start.

📸 Verified Output:


Step 3: Capture Groups — Extracting Data

Use () to capture parts of a match. Named groups (?<name>) make code self-documenting.

💡 matchAll requires the g flag and returns an iterator of all matches with full group info. Unlike .match(pattern) with g which only returns the matched strings, matchAll gives you each match's index and groups.

📸 Verified Output:


Step 4: Search and Replace

str.replace() and str.replaceAll() with regex are powerful text transformation tools.

💡 The replacement function receives (fullMatch, group1, group2, ..., offset, originalString). This lets you transform captured values dynamically — price calculations, case conversion, template filling, etc.

📸 Verified Output:


Step 5: Real-World — Form Validation

Build a validator using regex patterns.

💡 Lookahead (?=...) is what makes the password regex work: each (?=.*[A-Z]) asserts "the string contains at least one uppercase letter" without consuming characters. Multiple lookaheads stack as AND conditions.

📸 Verified Output:


Step 6: Log Parsing — Extract Structured Data

Parse Apache-style access logs with regex.

💡 Named groups make log parsing readable. Instead of remembering m[4] is the path, m.groups.path is self-documenting. This approach scales to complex formats like nginx, syslog, or custom JSON-adjacent logs.

📸 Verified Output:


Step 7: Sticky and Lookaround

Advanced patterns: sticky flag y, lookahead (?=), lookbehind (?<=), negative variants.

💡 Lookaheads/lookbehinds are zero-width — they check context without including it in the match. This lets you extract "the number after $" or "the word before :" without capturing the delimiter itself.

📸 Verified Output:


Step 8: Build a Mini Template Engine

Use regex replace to build a lightweight {{variable}} template engine.

💡 Template engines (Handlebars, Mustache, EJS) use regex at their core. This 15-line version handles dot notation, missing key behavior, and strict mode — demonstrating how much regex can accomplish elegantly.

📸 Verified Output:


Verification

Expected: Template renders correctly with data substitution and strict error on missing key.

Common Mistakes

Mistake
Fix

Forgetting g flag for all matches

Without g, only first match is found

Using test() with stateful g regex

lastIndex advances — create new regex or reset

Overescaping in string constructors

new RegExp('\\d+') needs double backslash

Greedy vs lazy quantifiers

.*? is lazy (minimal), .* is greedy (maximal)

Not escaping user input in dynamic regex

Use `str.replace(/[.*+?^${}()

Summary

You've covered regex literals and constructors, all major character classes and quantifiers, capture groups (named and unnamed), global matching with matchAll, powerful replacements with functions, form validation, log parsing, lookahead/lookbehind, and building a template engine. Regex is now a tool you can reach for confidently.

Further Reading

Last updated