A Beginner's Guide to Regular Expressions
February 10, 2025 · 10 min read
What Are Regular Expressions?
Regular expressions (regex or regexp) are sequences of characters that define a search pattern. They are used for pattern matching within strings — finding, replacing, or validating text. Virtually every programming language supports regex, making it one of the most universally useful skills a developer can learn.
While regex can look intimidating at first glance, the core concepts are surprisingly simple. This guide will walk you through the fundamentals step by step.
Basic Syntax
Literal Characters
The simplest regex is just a literal string. The pattern hello matches the exact text "hello" within any string.
Metacharacters
Special characters with special meaning in regex:
| Token | Meaning | Example |
|---|---|---|
| . | Any single character | h.t → hat, hot, hit |
| ^ | Start of string | ^Hello → matches "Hello world" |
| $ | End of string | world$ → matches "Hello world" |
| \d | Any digit (0-9) | \d\d → 42, 99 |
| \w | Word character (a-z, A-Z, 0-9, _) | \w+ → hello_123 |
| \s | Whitespace character | hello\sworld |
Quantifiers
Quantifiers control how many times a pattern should repeat:
| Quantifier | Meaning | Example |
|---|---|---|
| * | 0 or more | ab*c → ac, abc, abbc |
| + | 1 or more | ab+c → abc, abbc (not ac) |
| ? | 0 or 1 (optional) | colou?r → color, colour |
| {n} | Exactly n times | \d{3} → 123 |
| {n,m} | Between n and m times | \d{2,4} → 12, 1234 |
Character Classes
Square brackets define a character class — a set of characters to match:
[abc] → matches a, b, or c [a-z] → matches any lowercase letter [A-Za-z] → matches any letter [0-9] → matches any digit (same as \d) [^abc] → matches anything EXCEPT a, b, or c
Groups and Alternation
Parentheses create capture groups, and the pipe | acts as OR:
(cat|dog) → matches "cat" or "dog"
(\d{3})-\d{4} → matches "123-4567" and captures "123"
(?:abc) → non-capturing group (matches but doesn't capture)Practical Examples
Validate an Email Address
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
// Matches: [email protected], [email protected]
// Rejects: @invalid, user@, [email protected]Extract Phone Numbers
\+?\d{1,3}[-.\s]?\(?(\d{3})\)?[-.\s]?(\d{3})[-.\s]?(\d{4})
// Matches: +1-234-567-8901, (234) 567-8901, 2345678901Match a URL
https?:\/\/[\w.-]+\.[a-z]{2,}(\/\S*)?
// Matches: https://tools.ansasolutions.in/tools/regex-testerTips for Writing Better Regex
- Start simple: Build your pattern incrementally, testing at each step.
- Use a tester: Always validate your regex with real test data before deploying.
- Be specific: Prefer
[a-z]over.when you know the expected characters. - Watch for greedy matching: Use
*?or+?for non-greedy (lazy) quantifiers. - Comment complex patterns: Use the verbose flag (
x) in languages that support it.
Try it yourself
Test and debug your regex patterns with live highlighting and match info.