How Regular Expressions Work (A Beginner's Guide)
Last updated 2026-09-12
A regular expression (regex) is a pattern that describes text to search for — instead of matching an exact string, it matches a shape of text.
Start with literal characters
Most characters in a pattern just match themselves — the pattern "cat" matches the literal text "cat" wherever it appears.
Use character classes for flexibility
\d matches any digit, \w matches any word character (letters, digits, underscore), and \s matches whitespace. A custom class like [aeiou] matches any one of those characters.
Use quantifiers to repeat
+ means "one or more," * means "zero or more," and {2,4} means "between 2 and 4 times." So \d+ matches one or more digits in a row.
Add flags to change behavior
The "g" flag finds all matches instead of just the first; "i" makes matching case-insensitive.
Example
The pattern \d+ against "Order #12, order #345" matches "12" and "345" — one or more digits, wherever they appear.
Important Considerations
- Regex is powerful but easy to overuse — for simple exact matches or splits, a plain string method is often clearer and faster.
- Certain characters (. * + ? ( ) [ ] { } ^ $ |) have special meaning and must be escaped with a backslash to match them literally.
- Complex regex patterns can become hard to read — breaking a problem into two simpler steps is often better than one dense pattern.
Frequently Asked Questions
- What's the difference between * and +?
- * matches zero or more occurrences (so it can match nothing), while + requires at least one occurrence.
- How do I match a literal period?
- Escape it with a backslash: \. — an unescaped period matches any single character, not just a literal dot.