Regex Basics: A Beginner's Guide
Published 10/10/2025 · 3 min read · Developer tools
Daniel Okonkwo — Front-end developer and tech writer at Allin
Web performance · File formats
Checked against 2 sources
A regular expression (regex) is a pattern for matching text. The essentials: literal characters match themselves, . matches any character, \d matches a digit, \w a word character, \s whitespace; * means zero or more, + one or more, ? optional; [abc] matches any listed character, ^ and $ anchor to the start and end. So \d{3}-\d{4} matches a phone number like 555-1234.
A regular expression is a pattern for matching text. Here are the building blocks — character classes, quantifiers and anchors — with a worked example.
What regex is for
A regular expression describes a pattern rather than an exact string, which lets you search, validate, extract and replace text far more flexibly. Instead of hunting for one fixed phone number, you describe the shape of any phone number and match them all. They power find-and-replace in editors, form validation, and pulling data out of logs and text.
The building blocks
Most of a pattern is literal text that matches itself. Where text varies, you use character classes: \d matches any digit, \w a word character (letters, digits, underscore), \s any whitespace, and the dot . matches almost any single character. A set in square brackets like [aeiou] matches any one character you list, and [^0-9] matches anything except those.
Quantifiers and anchors
Quantifiers say how many times the previous item may repeat: * is zero or more, + is one or more, ? is optional (zero or one), and {3} means exactly three, {2,4} between two and four. Anchors pin the match in place: ^ marks the start of the text and $ the end, so ^abc$ matches only the exact string 'abc'. Parentheses ( ) group parts together.
A worked example
To match a phone number like 555-1234, describe its shape: three digits, a hyphen, four digits. That is \d{3}-\d{4}. To also allow an optional area code in brackets, you might extend it step by step, testing as you go. Note that quantifiers are greedy by default — they grab as much as they can — which is worth remembering once patterns get longer.
Frequently asked questions
- What does \d mean in regex?
- It matches any single digit, 0 through 9. So \d{3} matches exactly three digits in a row.
- What's the difference between * and +?
- * matches zero or more of the preceding item, while + matches one or more — so + requires at least one occurrence.
- Are regex the same in every language?
- The core syntax is shared, but details and flavours differ between JavaScript, Python, PCRE and others — check your language's docs for edge cases.
Articles you may find interesting
All guides →Related tools
Sources
Spotted a mistake in this article?