Course:Internet & Tools/
Lesson

Every developer eventually hits a moment where they need to check whether a string looks like an email, pull a phone number out of a log file, or swap every date format in a document. You could write a loop and check character by character, or you could write one line of regexWhat is regex?A compact pattern language for matching, searching, and replacing text, built into nearly every programming language and code editor. and be done in seconds.

Regular expressions (often shortened to "regex") are a compact language for describing text patterns. They are not a JavaScript feature or a Python feature, they are a concept built into almost every programming language and many tools you already use, from your code editor's search bar to command-line utilities like grep.

What regexWhat is regex?A compact pattern language for matching, searching, and replacing text, built into nearly every programming language and code editor. actually does

A regex pattern is a description of text you want to match. The engine reads your pattern and scans an input string, looking for any part that fits the description.

// Does the string contain a sequence of three digits?
/\d{3}/.test('Order #123 shipped');  // true
/\d{3}/.test('Order shipped');       // false

// Find all email addresses in a block of text
const text = 'Contact hello@example.com or support@site.org';
const emails = text.match(/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z]{2,}\b/gi);
// ['hello@example.com', 'support@site.org']

The pattern is the part between the / slashes. Everything after the closing slash is a flag, g means "find all matches," i means "ignore case." You will learn all of these piece by piece throughout this moduleWhat is module?A self-contained file of code with its own scope that explicitly exports values for other files to import, preventing name collisions..

02

Four things developers use regexWhat is regex?A compact pattern language for matching, searching, and replacing text, built into nearly every programming language and code editor. for

Use caseWhat it doesExample
ValidationCheck that input matches an expected shapeVerify an email format before saving
Search and replaceFind patterns and swap them in one callRedact phone numbers in a log file
Data extractionPull structured pieces out of unstructured textExtract IP addresses from server logs
Format transformationRearrange or normalize formatsConvert YYYY-MM-DD to DD/MM/YYYY

Validation

Checking that user input matches an expected shape before you process it or store it is one of the most common uses.

const isValidEmail = email => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);

isValidEmail('user@example.com'); // true
isValidEmail('invalid-email');    // false

Search and replace

You can find patterns and replace them with something else, in one call, across an entire string.

const text = 'Call me at 555-1234 or 555-5678';
const redacted = text.replace(/\d{3}-\d{4}/g, '[REDACTED]');
// 'Call me at [REDACTED] or [REDACTED]'

Data extraction

Pulling structured pieces out of unstructured text, log files, APIWhat is api?A set of rules that lets one program talk to another, usually over the internet, by sending requests and getting responses. responses, user input, is where regex really earns its keep.

// Extract the IP address from a server log line
const log = '192.168.1.1 - - [10/Oct/2023] "GET /api" 200';
const ip = log.match(/^(\d+\.\d+\.\d+\.\d+)/)?.[1];
// '192.168.1.1'

Format transformation

Rearranging date formats, normalizing phone numbers, or converting one naming convention to another.

// Convert YYYY-MM-DD to DD/MM/YYYY
const date = '2024-03-15';
const reformatted = date.replace(/(\d{4})-(\d{2})-(\d{2})/, '$3/$2/CODE_BLOCK');
// '15/03/2024'
03

RegexWhat is regex?A compact pattern language for matching, searching, and replacing text, built into nearly every programming language and code editor. and AI: an honest warning

AI assistants generate regex all the time. This is genuinely useful, but it comes with a serious caveat. AI does not verify what it generates, it produces patterns that look plausible based on training data, not patterns it has actually tested against your specific edge cases.

Common problems with AI-generated regex:

  • Patterns that work on the happy path but fail silently on edge cases
  • Overly complex expressions that are impossible to maintain or debug
  • Patterns with catastrophic backtracking that can freeze or crash a server under adversarial input
  • Patterns that are more restrictive than necessary, rejecting valid input

Your job is not to generate regex, your job is to read it, understand it, test it, and make a call about whether it is fit for production. The restWhat is rest?An architectural style for web APIs where URLs represent resources (nouns) and HTTP methods (GET, POST, PUT, DELETE) represent actions on those resources. of this moduleWhat is module?A self-contained file of code with its own scope that explicitly exports values for other files to import, preventing name collisions. gives you the vocabulary to do that.

When you get regex from AI, always paste it into regex101.com before using it. The visual breakdown will tell you immediately if something looks off.
04

How to learn regexWhat is regex?A compact pattern language for matching, searching, and replacing text, built into nearly every programming language and code editor. effectively

Do not try to memorize the entire syntax upfront. Instead, build the skill in layers.

// Start with literal matching
/hello/.test('say hello world'); // true - contains the word

// Then add anchors for exact matching
/^hello$/.test('hello');       // true - exactly this word
/^hello$/.test('hello world'); // false - there is more after it

// Then add character classes and quantifiers
/^\d{5}$/.test('90210'); // true - exactly 5 digits
/^\d{5}$/.test('9021');  // false - only 4 digits
05

Quick reference

ToolWhat it is for
regex101.comLive tester with visual explanation of each part
regexr.comAlternative tester with a community pattern library
MDN Regex GuideComprehensive reference for JavaScript-flavored regex
Your browser consoleQuick tests without leaving your workflow
javascript
// Testing regex patterns
const tests = [
  { pattern: /hello/, input: 'hello world', expected: true },
  { pattern: /world$/, input: 'hello world', expected: true },
  { pattern: /^hello/, input: 'say hello', expected: false },
  { pattern: /\d+/, input: 'abc123def', expected: true },
  { pattern: /[aeiou]/i, input: 'HELLO', expected: true },
];

tests.forEach(({ pattern, input, expected }) => {
  const result = pattern.test(input);
  const status = result === expected ? '✅' : '❌';
  console.log(`${status} /${pattern.source}/ test("${input}") = ${result} (expected ${expected})`);
});

// Extracting data with match
const phonePattern = /\(?(\d{3})\)?[-.\s]?(\d{3})[-.\s]?(\d{4})/;
const phone = '(555) 123-4567';
const match = phone.match(phonePattern);
if (match) {
  console.log('Area code:', match[1]);  // '555'
  console.log('Prefix:', match[2]);     // '123'
  console.log('Line:', match[3]);       // '4567'
}