Mastering Regular Expressions: The Developer Guide to Regex
A regular expression (abbreviated as regex or regexp) is a sequence of characters that specifies a search pattern in text. Regex is one of the most powerful utilities in a developer's toolkit for input validation, string parsing, and find-and-replace text manipulations.
In this guide, we'll break down the syntax, character classes, capture groups, and flags, along with common code snippets.
Regex Anatomy: Literal vs. Metacharacters
A regular expression is composed of a mix of literal characters and metacharacters:
- Literals: Characters that match themselves directly (e.g.
catmatches exactly the characters "c", "a", "t"). - Metacharacters: Characters with structural meaning (e.g.
.matches any character except a newline,^asserts the start of a line, and$asserts the end).
Core Syntax & Token Cheat Sheet
1. Character Classes
[abc]: Matches eithera,b, orc.[^abc]: Matches any character *except*a,b, orc(negation).\d: Matches any digit (same as[0-9]).\w: Matches any word character (alphanumeric and underscore).\s: Matches any whitespace character (space, tab, newline).
Regex Tester
Test and debug regular expressions online with real-time match highlighting, group capture extraction, and flag toggles client-side in the browser.
2. Quantifiers
*: Matches 0 or more occurrences.+: Matches 1 or more occurrences.?: Matches 0 or 1 occurrence (makes the token optional).{n}: Matches exactlynoccurrences.{n,m}: Matches betweennandmoccurrences.
3. Capture Groups and Anchors
(abc): Captures the match segment to index groups (e.g.$1,$2).(?:abc): Matches the segment but does not capture it (non-capturing group).\b: Asserts a word boundary.(?=abc): Positive lookahead. Asserts that the pattern matches ahead, but does not include it in the match selection.
Regular Expression Flags
Flags modify the matching behavior of the expression:
- `g` (Global): Matches all instances in the target string instead of stopping at the first match.
- `i` (Case-insensitive): Ignores uppercase/lowercase differences.
- `m` (Multiline): Treat beginning
^and ending$assertions as matching individual lines instead of the complete string. - `s` (DotAll): Allows the dot
.wildcard to match newline characters.
JavaScript Usage Example
In JavaScript, you can write regular expressions as literals enclosed in slashes or compile them using the RegExp constructor:
// Test if a string contains email
const emailRegex = /\b[A-Za-50._%+-]+@[A-Za-z0-9.-]+\.[A-Za-5]{2,}\b/i;
const isEmail = emailRegex.test("support@cosharex.com");
console.log(isEmail); // Output: true