Regular Expressions Explained — A Beginner's Guide with Examples
Regular expressions look scary but they're incredibly useful. Learn the basics with practical examples you can try right now.
Regular expressions (regex) are one of those things that look like your cat walked across the keyboard. But once you understand the basics, they become one of the most powerful tools in your toolkit. They let you search, match, and manipulate text patterns in ways that would take dozens of lines of code otherwise.
What regex actually does
At its simplest, regex is a pattern that describes text. The pattern cat matches the literal text "cat." Not very exciting. But c.t matches "cat," "cot," "cut," and any three-letter word starting with c and ending with t. That dot is a wildcard — it matches any character.
The essential building blocks
. — Matches any single character. h.t matches "hat," "hit," "hot."
* — Matches zero or more of the previous character. ab*c matches "ac," "abc," "abbc," "abbbc."
+ — Matches one or more of the previous character. ab+c matches "abc," "abbc" but NOT "ac."
? — Makes the previous character optional. colou?r matches both "color" and "colour."
[abc] — Matches any one of the characters inside. [aeiou] matches any vowel.
\d — Matches any digit (0-9). \d{3} matches any three digits.
^ and $ — Match the start and end of a line. ^Hello matches "Hello" only at the beginning.
Real-world examples
Email validation: [a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}
Phone numbers: \(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}
URLs: https?://[\w.-]+\.[a-zA-Z]{2,}(/\S*)?
These patterns look complex, but they're just combinations of the basic building blocks.
Testing your patterns
The best way to learn regex is to experiment. Toolozo's Regex Tester lets you type a pattern and test text, seeing matches highlighted in real-time. It's invaluable when you're trying to get a pattern right before using it in your code.
Frequently Asked Questions
Is regex the same in all programming languages?
The core syntax is mostly the same, but there are dialect differences. JavaScript, Python, and Java all support slightly different features. Test in your target language.
How do I learn regex faster?
Practice with real examples using a regex tester. Start with simple patterns and build up. The most common patterns (email, phone, URL) cover 90% of real-world use cases.