Regular expressions for beginners: a practical guide
By TabBenchHow we check our guides
A Regular Expression (regex) is a sequence of characters that specifies a search pattern in text. Ubiquitous across software development, data parsing, form validation, and command-line search tools like grep, regex allows you to match complex textual rules with a single string.
While regex syntax can appear cryptic at first glance, it is built on a few logical building blocks: literal characters, character classes, quantifiers, anchors, and capture groups.
Step by step
Understand Character Classes & Shorthands
`\d` matches any digit (0-9). `\w` matches any word character (letters, numbers, underscore). `\s` matches whitespace (spaces, tabs, newlines). `.` matches any character except newline. Bracket notation `[a-z]` matches any lowercase letter.
Master Quantifiers: How Many Times to Match
`*` matches 0 or more times. `+` matches 1 or more times. `?` matches 0 or 1 time (optional). `{3}` matches exactly 3 times. `{2,5}` matches between 2 and 5 times. Quantifiers are greedy by default; append `?` (`*?`, `+?`) for non-greedy matching.
Use Anchors to Bind Positions
`^` matches the beginning of a line or string. `$` matches the end of a line or string. For example, `^\d{5}$` validates that an entire string consists of exactly 5 digits (a US ZIP code) with no leading or trailing characters.
Group and Capture Patterns with Parentheses
Parentheses `(abc)` create a capture group, allowing you to apply quantifiers to blocks or extract matched substrings. Non-capturing groups `(?:abc)` group patterns without saving memory overhead.
Things worth knowing
- Always escape special regex characters (`.`, `*`, `+`, `?`, `^`, `$`, `(`, `)`, `[`, `]`, `\`, `/`) with a preceding backslash when matching them literally.
- The `i` flag enables case-insensitive matching; the `g` flag enables global matching across the entire text; the `m` flag enables multi-line mode.
- Avoid nested quantifiers like `(a+)+$` on untrusted inputs, as they can cause exponential catastrophic backtracking (ReDoS).
- Test your regular expressions in an interactive regex tester with live highlighting before deploying to production code.
Frequently asked questions
What is catastrophic backtracking (ReDoS)?
Can regex completely validate every valid RFC 5322 email address?
What is the difference between positive and negative lookaheads?
Why does `\d` match different characters in different languages?
Related tools
AI Code & Formula Explainer
Plain-English explanations of formulas, calculations and code.
Optional cloud mode
Text Diff Checker
Compare two texts and see exactly what was added or removed.
Cron Expression Explainer
Read cron schedules in plain English and build new ones.
Regex Builder
Build a regular expression from blocks, with live matches.