Back to roadmaps regex Course

Introduction to Regular Expressions and Pattern Matching

A Regular Expression (Regex) is a sequence of characters that defines a search pattern. It is used to find, extract, validate, or replace text within strings.


1. Why Use Regular Expressions?

Without regex, finding patterns in text requires complex, brittle string comparisons. With regex, you can write concise rules that match complex text patterns:

  • Validate that a form field contains a valid email address format.
  • Extract all phone numbers from a large document.
  • Find all timestamps in a log file and reformat them.
  • Replace all occurrences of an old domain name across many files.

2. Regex Engine Types

Different programming languages and tools use slightly different regex engine flavors. The most common is PCRE (Perl Compatible Regular Expressions), which is used by JavaScript, Python, PHP, and most modern tools. The syntax you learn in this module applies to PCRE.


3. Basic Literal Matching

The simplest regex is a literal string. The pattern hello matches any string that contains the exact sequence of characters hello:

// JavaScript example
const str = "Say hello to the world!";
const result = str.match(/hello/);
console.log(result[0]); // "hello"

4. Using Regex in JavaScript

JavaScript uses regex literals wrapped in forward slashes /pattern/flags or the RegExp constructor:

const text = "My phone number is 555-1234.";

// Test if pattern exists
/\d{3}-\d{4}/.test(text); // true

// Extract all matches
text.match(/\d+/g); // ["555", "1234"]

// Replace matches
text.replace(/\d{3}-\d{4}/, "REDACTED"); // "My phone number is REDACTED."
Published on Last updated: