Probador de Regex

Prueba y depura expresiones regulares con coincidencias en tiempo real, grupos y validación

What Are Regular Expressions?

Regular expressions (regex or regexp) are patterns used to match character combinations in strings. Defined by the ECMA-262 specification for JavaScript, regular expressions provide a powerful and concise syntax for searching, extracting, and replacing text. They are indispensable in input validation, log parsing, data extraction, search-and-replace operations, and URL routing. A regex pattern is compiled into an internal state machine that processes input characters sequentially, making it possible to express complex matching rules in a single compact expression rather than pages of procedural string-handling code.

Regular Expression Syntax

A regex pattern is composed of literal characters and metacharacters that define matching rules. Understanding the core building blocks is essential for writing correct and efficient patterns.

Character Classes

  • [abc] — matches any single character a, b, or c
  • [^abc] — negated class, matches anything except a, b, or c
  • [a-z] — range, matches any lowercase letter
  • \d — shorthand for [0-9] (any digit)
  • \w — shorthand for [A-Za-z0-9_] (word character)
  • \s — shorthand for whitespace (space, tab, newline, etc.)
  • . — wildcard, matches any character except newline (unless s flag is set)

Quantifiers

  • * — zero or more repetitions (greedy)
  • + — one or more repetitions (greedy)
  • ? — zero or one (optional)
  • {n} — exactly n repetitions
  • {n,m} — between n and m repetitions
  • *?, +?, {n,m}? — lazy (non-greedy) variants

Anchors

  • ^ — start of string (or start of line with m flag)
  • $ — end of string (or end of line with m flag)
  • \b — word boundary
  • \B — non-word boundary

Capture Groups and Backreferences

Parentheses (...) create capture groups that extract matched substrings for later use. Each group is numbered sequentially from left to right starting at 1, and the entire match is accessible at index 0. Groups are essential for extracting structured data from text, such as dates, URLs, email components, or log fields.

  • (abc) — capturing group, stores the matched text
  • (?:abc) — non-capturing group, groups without storing
  • (?<name>abc) — named capture group, accessible by name
  • \1, \2 — backreferences to previously captured groups
  • (?=abc) — positive lookahead, asserts that abc follows without consuming
  • (?!abc) — negative lookahead, asserts that abc does NOT follow
  • (?<=abc) — positive lookbehind, asserts that abc precedes
  • (?<!abc) — negative lookbehind, asserts that abc does NOT precede

Named groups improve readability in complex patterns. Instead of relying on numeric indices, you can access results via match.groups.name in JavaScript, making code more maintainable and self-documenting.

Flags and Modifiers

Flags modify how the regex engine interprets the pattern. In JavaScript, flags are appended after the closing delimiter (/pattern/flags) or passed as the second argument to the RegExp constructor.

  • g (global) — find all matches rather than stopping at the first
  • i (ignoreCase) — case-insensitive matching
  • m (multiline) — ^ and $ match line boundaries, not just string boundaries
  • s (dotAll) — makes . match newline characters as well
  • u (unicode) — enables full Unicode matching, treats surrogate pairs as single code points
  • v (unicodeSets) — extends u with set notation and string properties (ES2024)
  • d (hasIndices) — generates start/end indices for captured groups
  • y (sticky) — matches only at the position indicated by lastIndex

The u flag is strongly recommended when working with international text because without it, characters outside the Basic Multilingual Plane (like emoji) are treated as two separate surrogate code units, leading to incorrect match lengths and broken character class ranges.

Common Regex Patterns

These battle-tested patterns address frequent validation and extraction tasks encountered in web development:

  • Email (simplified): ^[\w.+-]+@[\w-]+\.[a-zA-Z]{2,}$
  • URL: ^https?:\/\/[\w.-]+(?:\.[a-zA-Z]{2,})(?:\/[^\s]*)?$
  • IPv4: ^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$
  • ISO date: ^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])$
  • Hex color: ^#(?:[0-9a-fA-F]{3}){1,2}$
  • Slug: ^[a-z0-9]+(?:-[a-z0-9]+)*$

Note that email validation via regex is inherently approximate — the actual specification (RFC 5322) permits syntax too complex for practical regex use. For production systems, validate the format with a simple regex and confirm deliverability by sending a verification email.

Regex Performance and Catastrophic Backtracking

Regular expressions use a backtracking engine by default in JavaScript. When a pattern contains nested quantifiers or overlapping alternatives, certain inputs can trigger exponential backtracking, causing the engine to examine an astronomical number of paths before determining that no match exists. This is known as catastrophic backtracking or ReDoS (Regular Expression Denial of Service).

A classic example is the pattern (a+)+b matched against a string of only a characters. Each additional a doubles the number of backtracking paths, resulting in O(2n) time complexity. In a server-side context, this can freeze the event loop and create denial-of-service vulnerabilities.

To prevent catastrophic backtracking, follow these guidelines: avoid nested quantifiers like (a+)+, use atomic groups or possessive quantifiers where supported, prefer specific character classes over broad wildcards, and test patterns with worst-case inputs before deploying. Tools like this regex tester help visualize match behavior and identify problematic patterns before they reach production.

Code Examples

Pattern matching and capture groups in JavaScript

// Named capture groups for structured extraction
const datePattern = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const match = '2024-03-15'.match(datePattern);
console.log(match.groups);
// → { year: "2024", month: "03", day: "15" }

// Global flag with matchAll for iterating all matches
const emailPattern = /[\w.+-]+@[\w-]+\.[a-zA-Z]{2,}/g;
const text = 'Contact alice@example.com or bob@dev.io';
const emails = [...text.matchAll(emailPattern)];
console.log(emails.map(m => m[0]));
// → ["alice@example.com", "bob@dev.io"]

// Lookahead for password validation (no consuming)
const strongPassword = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%]).{8,}$/;
console.log(strongPassword.test('Str0ng!Pass'));  // → true
console.log(strongPassword.test('weakpass'));     // → false

// Replace with backreference — swap first/last name
const name = 'Lopez, Francisco';
const swapped = name.replace(/(\w+),\s*(\w+)/, '$2 $1');
console.log(swapped); // → "Francisco Lopez"

Using RegExp constructor with dynamic patterns

// Build patterns dynamically from user input (escape special chars)
function escapeRegex(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

function highlightTerm(text, term) {
  const escaped = escapeRegex(term);
  const pattern = new RegExp(`(\\b${escaped}\\b)`, 'gi');
  return text.replace(pattern, '<mark>$1</mark>');
}

console.log(highlightTerm('The regex engine uses regex patterns', 'regex'));
// → "The <mark>regex</mark> engine uses <mark>regex</mark> patterns"

// Split with regex — handle multiple delimiter types
const csv = 'one, two;three | four';
const parts = csv.split(/\s*[,;|]\s*/);
console.log(parts); // → ["one", "two", "three", "four"]

Standards & Specifications

Preguntas Frecuentes

What is a regular expression?

A regular expression (regex) is a pattern used to match and manipulate text. It's a powerful tool for searching, validating, and extracting data from strings. Regex is used in programming, text editors, and many other tools.

What regex flags are supported?

Common flags include: g (global - find all matches), i (case-insensitive), m (multiline - ^ and $ match line boundaries), s (dotAll - dot matches newlines), and u (unicode). You can combine multiple flags.

Why is my regex slow?

Complex patterns with nested quantifiers or backtracking can cause performance issues. Patterns like (a+)+ are particularly problematic. The tool processes regex in a Web Worker to prevent freezing, but consider simplifying overly complex patterns.

Is my data sent to a server?

No, all regex testing happens in your browser. Your patterns and test data never leave your device. This ensures complete privacy and security for sensitive information.