Regex for Beginners: A Practical Introduction
Published · 5 min read
Regular expressions have a reputation for looking like line noise. A pattern such as ^\d{3}-\d{4}$ can be intimidating the first time you see it. The good news is that regex is built from a small number of pieces, and once you can read those pieces, most patterns stop looking mysterious. This introduction covers the parts you will use in almost every pattern, with short examples you can paste into a tester and try for yourself.
What a regular expression actually is
A regular expression, or regex, is a small description of a text pattern. You hand it to a regex engine along with some text, and the engine reports where the pattern matches. You can use that to search, to check that input has the right format, to pull values out of a document, or to find and replace.
Almost every programming language and many editors support regex. The core syntax is shared, though there are small differences between languages, which matter more once you move beyond the basics. For a longer explanation, see the what is regex lesson.
Literal characters: the simplest pattern
Most characters match themselves. The pattern cat matches the three letters c, a and t in that order, wherever they appear. It will match inside concatenate too, because regex looks for the sequence, not for whole words. Matching is case-sensitive by default, so cat does not match Cat.
A handful of characters have special meaning and must be escaped with a backslash when you want them literally. They are . * + ? ^ $ ( ) [ ] { } | \ and, in some contexts, /. To match a literal dot, write \.; to match a literal question mark, write \?. The escaping lesson lists the rules.
Matching one character from a set
Character sets
Square brackets match exactly one character from a list. [aeiou] matches one vowel. Ranges keep it short: [a-z] is any lowercase letter and [0-9] is any digit. A caret at the start negates the set, so [^0-9] means any character that is not a digit.
Notice that the caret means two different things depending on where it appears. Inside brackets, at the very start, it negates the set. Outside brackets, it is an anchor for the start of the text, which is covered below. Most special characters also lose their meaning inside a set, so [.] matches a literal dot without escaping.
Shorthand classes and the dot
Some sets are so common that they have shortcuts. \d is a digit, \w is a word character (letters, digits and underscore), and \s is whitespace such as a space, tab or newline. The uppercase versions \D, \W and \S mean the opposite. The dot . matches any single character except a newline, which makes it powerful and easy to overuse.
Quantifiers: saying how many
A quantifier follows a token and says how many times it may repeat. These four cover most needs:
?means zero or one, so the token is optional.colou?rmatches bothcolorandcolour.*means zero or more.+means one or more.\d+matches a run of digits of any length.{n}means exactly n, and{n,m}means between n and m.\d{4}matches exactly four digits.
By default, * and + are greedy: they match as much as they can and only give characters back if the rest of the pattern needs them. Adding ? after them, as in .*?, makes them lazy so they match as little as possible. This difference explains many surprising results, and the greedy vs lazy lesson shows it step by step.
Anchors and word boundaries
Anchors match a position rather than a character. ^ matches the start of the text and $ matches the end. Together they force the pattern to cover the entire input, which is what you want for validation. ^\d{5}$ accepts 12345 but rejects 123456 and abc12345.
The word boundary \b matches the edge between a word character and a non-word character. It is the tool for searching inside longer text: \bcat\b matches the word cat but not the letters inside concatenate. Learn more in the anchors and word boundary lessons.
\b\d{3}-\d{4}\bThe pattern above finds seven-digit numbers written as three digits, a dash and four digits, such as 555-0100, without matching part of a longer number.
Groups, alternation and flags
Groups
Parentheses group tokens so a quantifier can apply to all of them, and they also capture what was matched so your code can read it later. (ab)+ matches ab, abab and so on. If you only need grouping and not capturing, write (?:ab)+.
Alternation
The pipe | means or. cat|dog matches either word. Alternation has low precedence, so ^cat|dog$ means ^cat or dog$. Wrap the options in a group when you need them anchored together: ^(?:cat|dog)$.
Flags
Flags change how the whole pattern behaves. The most common are i for case-insensitive matching, g for finding every match instead of just the first (in JavaScript), and m for multiline mode, where ^ and $ match at the start and end of each line. See the flags lesson for the full list.
^Error:.*$With the m flag, this pattern returns every line of a log that starts with Error:.
Using regex in JavaScript and Python
Once you have a pattern, using it in code takes only a few lines. In JavaScript, a regex literal sits between slashes, with flags after the closing slash.
const log = "Error: disk full\nInfo: ok\nError: timeout";
const errors = log.match(/^Error:.*$/gm) ?? [];
console.log(errors); // ["Error: disk full", "Error: timeout"]
console.log(/^\d{5}$/.test("12345")); // trueIn Python, use the re module and write patterns as raw strings with an r prefix so backslashes are passed through unchanged.
import re
log = "Error: disk full\nInfo: ok\nError: timeout"
print(re.findall(r"^Error:.*$", log, re.M)) # ['Error: disk full', 'Error: timeout']
print(bool(re.fullmatch(r"\d{5}", "12345"))) # TrueMistakes almost every beginner makes
- Forgetting to escape the dot.
example.comalso matchesexampleXcom; writeexample\.com. - Leaving out anchors when validating. Without
^and$, a format check passes if the pattern appears anywhere in the input. - Leaning on
.*everywhere. It is greedy and crosses whatever lies in its path. A specific class like[^,]*is usually safer. - Trying to write the whole pattern at once. Build it piece by piece and test after each step.
- Assuming a match means the data is valid. Regex checks shape; it cannot tell you whether an email inbox exists or a date is real.
\b\d{3}-\d{4}\b becomes: a word boundary, three digits, a dash, four digits, a word boundary. If the sentence does not describe what you want, the pattern does not either.Where to go from here
The fastest way to learn regex is to use it on text you care about. Paste a sample into a tester, write the smallest pattern that matches one value, then widen it carefully. Keep the cheat sheet open for syntax, and when you need a common format like an email or a date, start from a tested pattern in the pattern library rather than writing it from scratch.
A simple routine helps the knowledge stick. Each time you write a pattern, collect three strings that should match and three that should not, then check the result against all six. Over a few weeks you will build an instinct for where patterns break, which is the real skill behind confident regex work.
Thirty short interactive lessons, from literal text to a capstone project, with instant feedback in your browser. Start the free regex course →
Frequently asked questions
- Is regex hard to learn?
- The basics are quick to learn because patterns are built from a small set of pieces. Reading complex patterns takes practice, but most everyday patterns use only literals, sets, quantifiers and anchors.
- What is the difference between `*` and `+`?
- `*` matches zero or more of the previous token, so it also succeeds when nothing is there. `+` requires at least one occurrence.
- Why does my pattern match part of a word?
- Regex looks for a sequence of characters anywhere in the text. Add word boundaries with `\b`, or anchors `^` and `$` when the pattern must cover the whole input.
- Does regex work the same in every language?
- The core syntax is shared, but features such as lookbehind, named group syntax and Unicode handling differ between languages and engines, so test patterns in the language you will use.
Related posts
- How to Extract Anything from Text with RegexA repeatable regex method for pulling codes, emails, dates and amounts out of messy text, with tested patterns and JavaScript and Python code.
- Regex vs AI: When to Use WhichRegex vs AI for text tasks: determinism, cost, privacy and speed versus flexibility, and how to combine the two safely in real projects.
- Password Validation with Regex (and When Not To)Build password rules with regex lookaheads, see why current NIST guidance favours length and blocklists, and check rules in Go or Rust without lookahead.