💻 Development2024-12-21•7 min read
Regular Expressions (Regex): A Beginner's Guide
Learn the fundamentals of regex pattern matching with practical examples you can use today.
📌 Key Takeaways
- ✓Regex is a pattern language for matching text
- ✓Start with simple patterns and build up
- ✓Use online testers to debug your expressions
- ✓Common patterns: email, phone, URL validation
What is Regular Expression?
Regular expressions (regex) are patterns used to match character combinations in text. They're incredibly powerful for validation, search, and text manipulation.
Basic Regex Syntax
Literal Characters
Most characters match themselves literally:
Pattern: hello Matches: "hello" in "hello world"
Special Characters
| Character | Meaning | Example |
|---|---|---|
. | Any character | h.t → hat, hot, hit |
\d | Any digit | \d\d\d → 123 |
\w | Word character | \w+ → hello |
\s | Whitespace | hello\sworld |
^ | Start of string | ^Hello |
$ | End of string | end$ |
Quantifiers
| Quantifier | Meaning | Example |
|---|---|---|
* | 0 or more | ab*c → ac, abc, abbc |
+ | 1 or more | ab+c → abc, abbc |
? | 0 or 1 | colou?r → color, colour |
{n} | Exactly n | \d{4} → 2024 |
{n,m} | Between n and m | \d{2,4} → 12, 123, 1234 |
💡 Pro Tip: Use our Regex Tester to experiment with patterns in real-time and see matches highlighted.
Common Regex Patterns
Email Validation
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
Phone Number (US)
^\(?\d{3}\)?[-. ]?\d{3}[-. ]?\d{4}$
URL
https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)
Character Classes
Square brackets define a set of characters to match:
[aeiou] → any vowel [0-9] → any digit (same as \d) [A-Za-z] → any letter [^0-9] → NOT a digit
Groups and Alternation
(cat|dog) → matches "cat" or "dog"
(\d{3}) → captures 3 digits as a group
⚠️ Performance Warning: Complex regex patterns can be slow. Avoid nested quantifiers like
(a+)+ which can cause catastrophic backtracking.
🛠️ Try These Tools
← More Articles
Last updated: 2024-12-21