Learn the basics of regular expressions (regex): how to match patterns, use character classes, quantifiers, and groups to find and validate text.
Step-by-Step Guide
Understand What Regex Is
A regular expression (regex) is a sequence of characters that defines a search pattern. It is used to find, validate, extract, or replace text. Regex is supported in almost every programming language and many text editors.
Match Literal Characters
The simplest regex is a literal string. The pattern `cat` matches the exact string "cat" in "concatenate" and "scat". By default, regex is case-sensitive: `Cat` does not match "cat".
Use Character Classes
`[abc]` matches any one of a, b, or c. `[a-z]` matches any lowercase letter. `[0-9]` matches any digit. `[^abc]` matches anything EXCEPT a, b, or c. Shorthand: `\d` = digit, `\w` = word character (letter/digit/_), `\s` = whitespace.
Use Quantifiers
`*` = zero or more | `+` = one or more | `?` = zero or one | `{3}` = exactly 3 | `{2,5}` = between 2 and 5. Example: `\d{3}-\d{4}` matches a phone segment like "555-1234". Add `?` after a quantifier to make it lazy (match as few as possible).
Use Anchors and Groups
`^` anchors to the start of a line; `$` anchors to the end. `(abc)` creates a capture group. `(cat|dog)` matches either "cat" or "dog". Example: `^\d{5}$` matches exactly a 5-digit ZIP code and nothing else.
Try Our Free Tool
Regex Tester
Frequently Asked Questions
Q: How do I match a literal dot or bracket?
A: Special characters like `.`, `*`, `+`, `?`, `(`, `)`, `[`, `]`, `{`, `}`, `^`, `$`, `|`, `\` must be escaped with a backslash. Use `\.` to match a literal dot, `\(` to match a literal parenthesis.
Q: What is the difference between greedy and lazy matching?
A: Greedy quantifiers (default) match as much as possible. Lazy quantifiers (add `?`) match as little as possible. Example: `<.+>` on "<b>bold</b>" matches the entire string; `<.+?>` matches just "<b>".
Q: Where can I test my regex?
A: Use our Regex Tester tool to write a pattern, enter test text, and see matches highlighted in real time. You can also view capture groups and get match details instantly.