Regular Expressions (Regex) Beginner's Guide
๐ 12 min read ยท Text & Code ยท Try Regex Tester โ
What is Regex?
A regular expression (regex or regexp) is a sequence of characters that defines a search pattern. Regex is used to search, match, extract, validate, and replace text. It is supported in virtually every programming language and is one of the most powerful tools in a developer's toolkit.
For example, the regex \d{3}-\d{4} matches phone number patterns like "555-1234". Once you understand the building blocks, you can write patterns to match almost any text structure.
Basic Syntax: Character Classes
| Pattern | Matches |
|---|---|
| . | Any character except newline |
| \d | Any digit (0-9) |
| \D | Any non-digit |
| \w | Word character (a-z, A-Z, 0-9, _) |
| \W | Non-word character |
| \s | Whitespace (space, tab, newline) |
| \S | Non-whitespace |
| [abc] | Any of: a, b, or c |
| [^abc] | Any character except a, b, c |
| [a-z] | Any lowercase letter |
| [A-Z] | Any uppercase letter |
| [0-9] | Any digit (same as \d) |
Quantifiers
| Quantifier | Meaning |
|---|---|
| * | Zero or more times |
| + | One or more times |
| ? | Zero or one time (optional) |
| {n} | Exactly n times |
| {n,} | At least n times |
| {n,m} | Between n and m times |
| *? +? ?? | Lazy (non-greedy) versions โ match as few as possible |
Anchors & Boundaries
^Start of string (or line with m flag)
$End of string (or line with m flag)
\bWord boundary โ position between a word char and non-word char
\BNon-word boundary
Groups & Alternation
(abc)Capturing group โ captures the matched text for later use
(?:abc)Non-capturing group โ groups without capturing
(?<name>abc)Named capturing group โ access by name
a|bAlternation โ matches a or b
(?=abc)Positive lookahead โ matches if followed by abc
(?!abc)Negative lookahead โ matches if NOT followed by abc
Practical Regex Examples
Email validation
^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$Matches standard email addresses. Not 100% RFC-compliant but covers 99% of real emails.
URL matching
https?:\/\/[^\s/$.?#].[^\s]*Matches http and https URLs.
Phone number (US)
^\+?1?[\s.-]?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$Matches US phone numbers in various formats.
Strong password
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$Requires lowercase, uppercase, digit, special char, min 8 chars.
IPv4 address
^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$Validates IPv4 addresses (0.0.0.0 to 255.255.255.255).
Hex color code
^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$Matches 3 or 6 digit hex color codes like #FFF or #FF5733.
Regex Flags
gGlobal โ find all matches, not just the first
iCase-insensitive โ match regardless of letter case
mMultiline โ ^ and $ match start/end of each line
sDotAll โ dot (.) matches newline characters too
uUnicode โ enables full Unicode support
Test Your Regex Patterns
Write and test regex patterns with real-time match highlighting in your browser.
Regex Tester โ